CSS – Auto height adjustment for div which contains floating elements

Update @ 2014-11-13: In web development, this approach is very common and usually we called it the clearfix hack.
CSS-Tricks – Force Element To Self-Clear its Children

We always use the float property to arrange the layout of a webpage. Consider the following html.

<style type="text/css">
  .child {
    float: left;
    padding-top: 20px;
    background-color: grey;
  }
</style>

<div id="parent">
  <div class="child" style="height: 80px;">text 1</div>
  <div class="child" style="height: 70px;">text 2</div>
  <div class="child" style="height: 60px;">text 3</div>
  <div class="child" style="height: 50px;">text 4</div>
</div>

<div>Followihg div</div>

 

As all the child div is floated, the #parent div will have 0 height.
css-auto-height-adjustment-1

This makes the layout less controllable. We wants the #parent div having the height value which is the same as the child elements. The following piece of CSS code could help.

<style type="text/css">
  #parent:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    font-size: 0px;
  }

  .child {
    float: left;
    padding-top: 20px;
    background-color: grey;
  }
</style>

<div id="parent">
  <div class="child" style="height: 80px;">text 1</div>
  <div class="child" style="height: 70px;">text 2</div>
  <div class="child" style="height: 60px;">text 3</div>
  <div class="child" style="height: 50px;">text 4</div>
</div>

<div>Followihg div</div>

 

Check it out.
css-auto-height-adjustment-2
 

Done =)

4 thoughts on “CSS – Auto height adjustment for div which contains floating elements”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.