The height of the parent div is zero, even if it has a child with finite heights

I have a website whose layout is shown in the diagram. The body consists of a main container , which consists of a header , parent div and footer . parent div also contains several child div , as shown.

Webpage layout

The task, which is the height of all child div , is finite. But the parent div contains nothing but child divs. All child divs are visible, but the height of the parent div is zero. I also do not fix the height of the parent div by setting some given value, as this may cause an error if the number of children increases in the future.

The problem due to the zero size of the parent div is that my footer goes up and collides with the contents of the parent div. This can be resolved by providing a suitable margin, but this is not the solution I'm looking for.

Can someone suggest me a way for the height of the parent div to automatically change depending on the height of the child divs.

Please comment if I'm unclear, asking my doubts!

+47
css css3 height parent-child
Sep 22 '12 at 3:29
source share
2 answers

It looks like you got a case for the clearfix class .

So, I assume that you are floating the child div and therefore the height of the parent div is 0. When you use the float, the parent does not adapt to the height of the children.

But by adding the clearfix class (of course, you should have it in your stylesheet), it will add '.' at the end (invisible, of course), and your parent will magically have the correct height.

Please note that this is cross-platform compatible with IE6 +, Chrome, Safari, Firefox, you name it!

 .clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix { display: inline-block; } html[xmlns] .clearfix { display: block; } * html .clearfix { height: 1%; } 
+64
Sep 22
source share
— -

Try adding the following to your stylesheet:

 #parentdiv:after { content: " "; display: block; clear: both; } 

As Daedalus said in his comment, you are probably swimming with child divs. If so, the line above corrects it.

The problem when you are swimming is that their parent element “ignores” them.

The line above creates and inserts a (pseudo) element in #parentdiv that pushes past all floating divs. Then the parent div, which, despite ignoring the floating children, does not ignore this pseudo-element - acting as it should, it expands to contain the pseudo-element. Now, since the pseudo-element is below all movable children, the parent div happens or, even better, it seems to “contain” also the floating children, which is what you want.

+37
Sep 22 '12 at 4:01
source share



All Articles