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 =)

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s