Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 383
user4756836 Avatar asked May 16 '15 02:05

user4756836


People also ask

Can we set the margins for an element?

Answer: You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.


3 Answers

You have small mistake

Change:

.work img:not(:last)

to

.work:not(:last-child)

Check Fiddle Here.

like image 121
ketan Avatar answered Oct 17 '22 07:10

ketan


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

like image 31
Redy S Avatar answered Oct 17 '22 08:10

Redy S


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;
}
like image 37
Sean Stopnik Avatar answered Oct 17 '22 08:10

Sean Stopnik