Reputation: 1337
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
Reputation: 19341
You have small mistake
Change:
.work img:not(:last)
to
.work:not(:last-child)
Check Fiddle Here.
Upvotes: 77
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
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