Margin on every element except last

user4756836 picture user4756836 · May 16, 2015 · Viewed 20.4k times · Source

I have 2 lines of CSS for setting margin on every element except the last one. Is there a way to combine it into 1 line?

This is what I have currently(working):

.work img {
    margin-right: 10px;
}

.work img:last {
    margin-right: 0px;
}

I tried changing it to:

.work img:not(:last) {
    margin-right: 10px;
}

But it is not working? Any idea why?

UPDATE I have only five images. My other option would be to only have margins on the first four.

Answer

ketan picture ketan · May 16, 2015

You have small mistake

Change:

.work img:not(:last)

to

.work:not(:last-child)

Check Fiddle Here.