Monday, December 9, 2013

How to prevent container element with floats from collapsing?

Everybody knows that having number of floated elements inside of a container will cause outside container to collapse. If you look at the code below its not surprising that someContainer div will fold as three boxes inside of it are floated:

HTML:

<div class="someContainer">
    <div class="someFloat">Float 1</div>
    <div class="someFloat">Float 2</div>
    <div class="someFloat">Float 3</div>
</div>

CSS:

.someContainer
{
    border: 1px solid green;   
}

.someFloat
{
    width: 100px;
    height: 100px;
    border: 1px solid #f00;
    float: left;
}

Now, the most common solution to prevent someContainer from collapsing is to use some sort of clearfix at the end of someContainer div. Its usually class involving clear: both. Its sort of dirty solution as it pollutes HTML with unnecessary markup. There is pure CSS solution to this problem and its as simple as adding overflow: auto to someContainer class. Modified CSS is below, I also created fiddle in here:

CSS:

.someContainer
{
    border: 1px solid green;   
          overflow: auto;
}

.someFloat
{
    width: 100px;
    height: 100px;
    border: 1px solid #f00;
    float: left;
}

In my opinion this solution is way cleaner and faster then ever popular clearfix. It does the trick in most cases and even old and already forgotten browsers.

 

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from JQuery Training in Chennai . or learn thru JQuery Training . or learn thru ES6 Online Training. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete