emrzoa
Last Updated: February 25, 2016
·
5.947K
· 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!

Say Thanks
Respond

9 Responses
Add your response

13359
3c884f9f79fde96606153999a211f6b5

Sweet, thanks mate :)

over 1 year ago ·
13361

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

over 1 year ago ·
13363
F5adcb75cd4aa3b18ed5c01c97599b5b

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 ·
13365

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

over 1 year ago ·
13411
Logo normal

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 ·
13412

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 ·
13413
03ba33ccbb0ef8b3849096c1fe8f48e6

Likewise, you can also do it the opposite way around

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

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 ·
13493

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

over 1 year ago ·