Space between two divs

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.

-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 ;)


You can try something like the following:


or instead of the first h1 rule:


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

div + div{

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

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.

You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically


.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; } { background: #F00; margin-bottom: 50px;  }

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>‚Äč

Here is a jsfiddle example:


DIVs inherently lack any useful meaning, other than to divide, of course.

Best course of action would be to add a meaningful class name to them, and style their individual margins in CSS.

<h1>Important Title</h1>
<div class="testimonials">...</div>
<div class="footer">...</div>

h1 {margin-bottom: 0.1em;}
div.testimonials {margin-bottom: 0.2em;}
div.footer {margin-bottom: 0;}

Need Your Help

width different from 100% for div container

javascript html css three.js

I have a simple WebGL code which displays a 3D graph. It works well but I would like to set a value for the width different from 100%; i.e I would like to put the webGL animation in a small box.

Attempting to send action on controller, causes unit test to fail for Ember.js

unit-testing ember.js

I am attempting to test that calling the move action will cause a modal view's controller to setup with the proper model.