May 15, 2013

How CSS float works? Why height of the container element doesn't increase if it contains floated elements

Boy Pasmo’s Question:

I would like to ask on how height and float works. I have this outside Div and an inner Div that has content in it. It’s height my vary depends on the content of the Inner Div but It seems that my inner div will overflow with it’s outside Div. What would be the proper way to do it? Any help would be much appreciated. Thanks!

<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange">
    <div style="width:500px; height:200px; background-color:black; float:right">

The floated elements do not add to the height in the container element, and hence if you don’t clear them, container height won’t increase…

I’ll show you a pictorial way

enter image description here

enter image description here

enter image description here

More Explanation:

  <div style="float: left;"></div>
  <div style="width: 15px;"></div> <!-- This will shift 
                                        beside the top div, why? because the top div 
                                        is floated to left, and hence making the 
                                        rest of the space blank -->

  <div style="clear: both;"></div> 
  <!-- Now in order to prevent the next div to float besides the top ones 
       we use `clear: both;`, this is like a wall, so now none of the div's 
       will be floated after here and also the container will now count the 
       height of these floated divs -->

My other answer here will explain you why we clear, though I’ve explained it here too

You can also add overflow: hidden; on container elements, but I would suggest you to use clear: both; instead.

Also if you might like to self clear an element you can use

.self_clear:after {
  content: "";
  clear: both;
  display: table;

Its because of the float of the div. Add overflow: hidden on the outside element.

<div style="overflow:hidden; margin:0 auto;width: 960px; min-height: 100px; background-color:orange;">
    <div style="width:500px; height:200px; background-color:black; float:right">


Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!