31

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.

user4756836
  • 1,035
  • 3
  • 17
  • 37
  • You may want to try .work img:last-child { margin-right: 0px } – Quintile May 16 '15 at 02:19
  • @Quintile that is still using 2 lines of CSS. I was just wondering if I could do it in one line. The first part of my code is working. Not the second part – user4756836 May 16 '15 at 02:20
  • The reason why is that there is no `:last` selector but we do have `:last-child` and `:last-of-type`. I was playing around with these selectors and thought it might help someone in the future: https://jsfiddle.net/21rs5dog/ – Dylan Valade May 16 '15 at 02:59
  • @DylanValade https://api.jquery.com/last-selector/ and :last works fine when you test it by itself like `img:last` – user4756836 May 16 '15 at 03:48
  • 1
    You're right, :last is a jQuery selector but your question was about CSS and CSS does not support it currently. – Dylan Valade May 17 '15 at 17:07

3 Answers3

39

You have small mistake

Change:

.work img:not(:last)

to

.work:not(:last-child)

Check Fiddle Here.

ketan
  • 17,717
  • 41
  • 50
  • 83
2

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;
}
Sean Stopnik
  • 1,685
  • 9
  • 9
1

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

Redy S
  • 322
  • 1
  • 6