Space between two divs

Fewfre picture Fewfre · Jun 13, 2012 · Viewed 113.2k times · Source

My issue is that I have two (or more) divs of the same class, that need to be spaced from each other. I cannot directly use margins however, as the last or first element would also have the margin applied, which I do not want.

example
-Green is where I want the space
-Red is where I don't want it

As the only solutions I can think of are complicated / involve hard-coding a value, I am hoping that someone can think of a clever, simple solution to this problem.

Details: Sometimes these divs would be by themselves, and on a rare occasion floated.

Any advice on how above ideas could be better, any new ideas, or just help in general would be greatly appreciated ;)

Answer

Christoph picture Christoph · Jun 13, 2012

You can try something like the following:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

or instead of the first h1 rule:

div:first-of-type{
   margin-top:<x>px;
}

or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{
   margin-bottom:<y>px;
}

Respectively, h1 + div would control the first div after your header, giving you additional styling options.