CSS - Add margin to button but only when two buttons used

Viewed 842

I have a demo here

Its a simple button inside a div

There is one button and then two buttons next to each other

I need to use the same button class for all the buttons

With the two button I need space between the buttons

I can do this with margin left and right but then that is used on the button on its own but I don't want it used when it's on it's own.

Is it possible to space the two buttons and have all the buttons use the same class.

.block{
  border: 1px solid #ddd;
  padding: 20px;
  width: 300px;
  display: flex;
  margin-bottom: 10px;

  .button{
    &:first-child {
        margin-right: 8px;
    }
    &:last-child {
        margin-left: 8px;
    }
  }
}


.button{
  border: 0;
  background: red;
  border-radius: 5px;
  color: white;
  padding: 10px;
  width: 100%;
}
2 Answers

You can apply margin-left: 8px to .button:nth-of-type(1n+2) - works for any number of buttons within the same parent. (1n+2 meaning each one [1n] starting at the second element [+2] of the same type)

(I added a blue border to the selected buttons to make the selection more obvious)

.block {
  border: 1px solid #ddd;
  padding: 20px;
  width: 300px;
  display: flex;
  margin-bottom: 10px;
}

.button {
  border: 0;
  background: red;
  border-radius: 5px;
  color: white;
  padding: 10px;
  width: 100%;
}

.button:nth-of-type(1n+2) {
  margin-left: 8px;
  border: 2px solid blue;
}
<div class="block">
  <button class="button">
    Button
  </button>
</div>

<div class="block">
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
</div>

Do it differently like below:

.block {
  border: 1px solid #ddd;
  padding: 20px;
  width: 300px;
  display: flex;
  margin-bottom: 10px;
}

.button {
  border: 0;
  background: red;
  border-radius: 5px;
  color: white;
  padding: 10px;
  width: 100%;
  margin:0 4px; /*margin to all*/
}

.button:first-child {
  margin-left: 0; /* remove the left from first */
}
.button:last-child {
  margin-right: 0; /* remove the right from last*/
}
<div class="block">
  <button class="button">
    Button
  </button>
</div>

<div class="block">
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
</div>

<div class="block">
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
  <button class="button">
    Button
  </button>
</div>

Related