Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Space between two divs

Tags:

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

like image 409
Fewfre Avatar asked Jun 13 '12 12:06

Fewfre


People also ask

Why is there a space between two divs?

Due to that floating , a white space has occurred between those two divs (between the div for header and div for main body). My question is, why this kind of problem is raising due to floating.? make sure your margin are all equal to 0 , so are the padding of your elements.

How do I give a space between two divs on flex?

To set space between the flexbox you can use the flexbox property justify-content you can also visit all the property in that link. We can use the justify-content property of a flex container to set space between the flexbox.


1 Answers

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.

like image 143
Christoph Avatar answered Sep 28 '22 14:09

Christoph