Little tip for spacing inline elements.

With inline elements you normally want spacing between, this is easy to do but when they are stacking horizontally it can lead to problems if not done properly.

‘natural’ approach

This what you’d probably try first off and rightly so, it makes sense – I want all my buttons to have a margin to the right apart from the last one.

Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
.btn {
  margin-right: 1em;
}

.btn:last-child {
  margin-right: 0;
}

‘conditional’ approach

This works for the equal spacing however when collapsed there’s unwanted left-most margin.

Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
.btn + .btn {
  margin-left: 1em;
}

‘negative-margin’ approach

Using a negative margin wrapper there’s equal margin between element. Only con for using this approach is you can’t style the background of the wrapper as it’ll bleed over your container width.

Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
Btn Text Btn Text Btn Text
.btn-group {
  margin-left: -.5em;
  margin-right: -.5em;
}

.btn-group > .btn {
  margin-left: .5em;
  margin-right: .5em;
}

End result works well, this is actually how Bootstrap’s grid system works for example.