September 22, 2015
All but the Last
.link {
margin-right: 1rem;
}
.link:last-child {
margin-right: 0;
}
Does this look familiar?
We use this a lot for list layouts where we want to have gutters, but not on the last element, otherwise it will get knocked down and wrap below.
Better Method
.link:not(:last-child) {
margin-right: 1rem;
}
Here we only have to set the margin once and with only one rule. This says, put margin-right: 1rem
on all .links
except the last. Easy peasy lemon squeezy. You can do the same thing with removing borders on first/last elements. I’m sure there are plenty of other great use cases you can find.