How to fix the issue of CSS collapsing parent having floating children

Topic: HTML / CSS« Prev|Next

Answer: Use the CSS clear Property

When float property applied to the element inside the non floated parent, the parent element doesn't stretch up automatically to accommodate the floated elements. This behavior is called collapsing parent. This is not always obvious if you do not apply some visual properties like background or borders to the parent elements, but it is important to be aware of and must dealt with to prevent strange layout and cross-browser problem.

Fixing Collapsing Parents in Current Browsers

The CSS :after pseudo-element in conjunction with the content property is used to resolve the collapsing parent issues in the browsers like Firefox, Chrome, Safari, IE8 and above.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Fixing Collapsing Parent Issue</title>
  • <style type="text/css"> 
  •     .clearfix:after{
  •         content:".";
  •         display:block;
  •         height:0;
  •         clear:both;
  •         visibility:hidden;
  •     }
  •     .container{
  •         background:yellow;
  •         border: 1px solid #000000;      
  •     }
  •     .column-left, .column-right{
  •         width: 200px;        
  •         margin: 10px;
  •         padding: 10px;
  •     }
  •     .column-left{
  •         float: left;       
  •         background: #ff0000
  •     }
  •     .column-right{
  •         float: right;
  •         background: #00ff00;
  •     }
  • </style>
  • </head>
  • <body>
  •     <div class="container clearfix">
  •         <div class="column-left">Floated to left.</div>
  •         <div class="column-right">Floated to right.</div>
  •     </div>
  • </body>
  • </html>

Check out the tutorial on CSS Alignment for more solutions on fixing collapsing parents.

Your Feedback:

We would love to hear from you, please drop us a line.