user4756836
user4756836

Reputation: 1337

Margin on every element except last

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.

Upvotes: 51

Views: 48892

Answers (3)

ketan
ketan

Reputation: 19341

You have small mistake

Change:

.work img:not(:last)

to

.work:not(:last-child)

Check Fiddle Here.

Upvotes: 77

Sean Stopnik
Sean Stopnik

Reputation: 1868

If you need full browser support, I would suggest using some javascript, or adding a class of .last on the last img. Otherwise you could just do:

.work img:last-child {
  margin: 0;
}

Upvotes: 3

Redy S
Redy S

Reputation: 372

Try this :

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

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

or

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

or jQuery solution :

jQuery('.work img:not(:last)').css({marginRight: 10);

Remember, your browser need to have support for selector if you apply pure CSS.

See this for reference: http://caniuse.com/#search=%3Alast-child

Upvotes: 6

Related Questions