Margin on every element except last

27,879

Solution 1

You have small mistake

Change:

.work img:not(:last)

to

.work:not(:last-child)

Check Fiddle Here.

Solution 2

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

Solution 3

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;
}
Share:
27,879
user4756836
Author by

user4756836

Updated on May 16, 2020

Comments

  • user4756836
    user4756836 about 4 years

    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.