Saturday, March 31, 2012

Prevent parent divs from collapsing under floated child divs

Sometimes when nesting a floating div, the child div overlaps the end of the parent div like in the image below. But what do you do when you want the child div to stay within the parent div?

Figure 1: The child div extends past the
parent div (BAD!).
Figure 2: The child div is nested within
the parent div (GOOD!).
Problem: The child div doesn't stay fully within the parent div.

Impact: The layout can get ruined (for instance, when using a border at the bottom of the parent div) when overlapping occurs.

Solution:
This problem occurs when the child div is floated but the parent is not. In your CSS, simply add float: left; or float: right; to your parent div's styling, whichever is appropriate. This will make sure the parent div stretches to encompass the child div.

0 comments:

Post a Comment