CSS – Deal with divs that only contain float divs
Situation:
You have a container with two or more elements with a class of box floated inside it.
Problem:
container height is 0, not getting its inner divs heights.
Example:
HTML:
1 2 3 4 5 6 7 8 9 10 |
<div class="container"> <div class="box"> <h1>Box 1</h1> <p>Hello, this is an offset101 example on box1.</p> </div> <div class="box"> <h1>Box 2</h1> <p>Hello, this is an offset101 example on box2.</p> </div> </div> |
CSS:
1 2 3 4 5 6 7 8 9 10 |
.container{ width: 500px; background-color: #fff; padding: 10px; } .box{ float: left; width: 50%; } |
But, if you see the container height with a background-color:red it’s going to be like this:
Possible solution 1 :
The first possible and clean solution, is floating the parent, so the CSS would be something like this:
1 2 3 4 5 6 7 8 9 10 11 |
.container{ width: 500px; background-color: red; padding: 10px; float:left; } .box{ float: left; width: 50%; } |
Possible solution 2 :
A second possible and clean solution, is adding and overflow to the parent, so the CSS would be something like this:
1 2 3 4 5 6 7 8 9 10 11 |
.container{ width: 500px; background-color: red; padding: 10px; overflow:auto; } .box{ float: left; width: 50%; } |
Applying any of those solutions above, the result will be as follows, letting the container get the heght of its inner divs: