Last Updated: October 06, 2020
·
6.54K
· sashagim

One liner CSS trick for spacing items

I often need to visually divide HTML items - whether by spacing, or in some other way. The simple way is:

.item {
    margin-right: 10px;
}

That's nice, we've got spacing! But.. that last item... It doesn't really need the margin, does it? So let's remove that:

.item {
    margin-right: 10px;
}

.item:last-child {
    margin-right: 0px;
}

But that's kinda silly, adding margin and then removing it! And what if we want to start spacing with a padding? We'll need to change it in two places. Horrible!

But this is pretty neat:

.item:not(:last-child) {
    margin-right: 10px;
}

Enjoy!

UPDATE

As mentioned in @mattandersen's comment, :not selector is not supported in IE before IE9, so his approach is better if support for earlier IEs is required:

.item+.item { margin-left: 10px; }

To clarify how it works -

.item1+.item2 

applies only for .item2 elements that come immediately after .item1. So

.item+.item

applies for all .item elements except the first one. Read more here: http://www.w3.org/TR/CSS21/selector.html#adjacent-selectors.

Thanks Matt!

9 Responses
Add your response

Sweet, thanks mate :)

over 1 year ago ·

Ah, I didn't know there is such thing as ":not" lolz

over 1 year ago ·

One that I ran across this year was instead to apply the margin on the left side, and ignore the spacing on the first item. This can be accomplished with the + selector, and has a support on IE back to 7.0.

.item+.item {
margin-left: 10px;
}

over 1 year ago ·

Nice Matt, that's cool as well! Thanks :)

over 1 year ago ·

While you’re at it, when a value is zero there’s no need to add the unit (px in this case)

over 1 year ago ·

Hey Nathan, thanks. I always wondered about this, but not enough to actually look it up. Now I did, and appears you're absolutely right: "for zero lengths the unit identifier is optional" (http://www.w3.org/TR/2013/CR-css3-values-20130730/#lengths)

over 1 year ago ·

Likewise, you can also do it the opposite way around

.item:not(:first-child) {
    margin-left: 10px;
}
over 1 year ago ·

Although its nearly mentioned in an earlier comment its worth noting that :not won't work IE <9 so if extensive compatibility is a concern that the + trick above is your man (if you really want to remove a few lines of CSS).

over 1 year ago ·

Thanks @mattstyles, I've updated the post to accommodate @mattandersen's comment.

over 1 year ago ·