Floating Elements in CSS

This tutorial is part of a web programming course for people who have no programming experience.


As you know, block-level elements in HTML stack up vertically by default. But sometimes you want them to line up horizontally, for example if you want to design a two column layout. In that case you would want to create two elements that line up side-by-side. You can acheive this effect by using the float property in CSS.

We'll start out with a page that looks like this, and we'll add HTML and CSS code to demonstrate various examples of 'floating' elements:

<!DOCTYPE html>
    <html>
        <head>
            <title>SAMPLE CODE - CSS FLOATS</title>
            <style type="text/css">
                html,h1,header{margin:0; padding:0; }
    
                /* ALL OF YOUR CSS CODE SAMPLES GO HERE */
            
            </style>
        </head>
        <body>
            <header>
                <h1>CSS Floating Elements</h1>
            </header>
            <div id="content">
                <main>
                    <h2>This is the main content area</h2>
    
                    <!-- ALL HTML CODE SAMPLES GO HERE -->
                
                </main>
                <aside>
                    <h2>This is the side bar</h2>
                </aside>
            </div>
            <footer>This is the footer</footer>
        </body>
    </html>

We'll start with a basic example of floating an element by adding this HTML code inside the MAIN element (under the H2 element).

<div id="outer">
    <div id="inner">
        I'm floating;
    </div>
</div>

Here is the CSS code to add to the STYLE element:

#outer{
    width:300px;
    height:200px;
    border:1px solid chocolate;
}

#inner{
    width: 150px;
    /*height: 100%;*/
    background-color: rosybrown;
    float:right;
}

The borders help you to see that the 'inner' DIV element is 'floating' on the right side of the 'outer' DIV. This is one way that you can go about adding a side bar to your web page. Let's go ahead and do just that by making the ASIDE element a side bar for our sample page. We'll do this by floating both the MAIN and ASIDE elements, and setting their widths to percentages:

main{
    float: left;
    width: 70%;
}

aside{
    float: left;
    width: 30%;
}

You should always set the width when you float an element. Otherwise, the results can be unpredictable. By using percentage widths, the elements become 'responsive' and adapt to various screen sizes. We'll dig deeper into responsive web pages in the next lesson.

If you look at the page in the browser, you'll see that the main and aside element show up side-by-side, but the footer seems to be out of place. To fix that, you can apply this hack.

#content{
    overflow: auto;
}

We'll explore some of the strange side affects of floating elements, as well as some ways to deal with them a little later.

Using Floats to Tile Elements

You can also float elements to create a tiling effect within your page layout. Add this HTML code to the MAIN element:

<div id="tile-container">
        <div class="tile">1</div>
        <div class="tile">2</div>
        <div class="tile">3</div>
        <div class="tile">4</div>
        <div class="tile">5</div>
        <div class="tile">6</div>
        <div class="tile">7</div>
        <div class="tile">8</div>
        <div class="tile">9</div>
        <div class="tile">10</div>
    </div>

And add this CSS code to the STYLE element:

#tile-container{
        border: 1px solid burlywood;
        width: 300px;
        height:200px;
    }
    
    .tile{ 
        width: 30px;
        height:30px;
        background-color: tomato;
        margin: 8px;
        line-height: 30px;
        text-align: center;
        float: left;
        /*change it to float right*/
    }

Responsive Tiles

In the previous example, the width of each tile was fixed at 30px. You could use percent widths to make your tiles 'responsive'. Here's the HTML code:

<div id="responsive-tiles-container">
        <div class="responsive-tile">1</div>
        <div class="responsive-tile">2</div>
        <div class="responsive-tile">3</div>
    </div>

Here's the CSS code:

.responsive-tile{
        width:20%;
        height:200px;
        background-color: lemonchiffon;
        margin: 6%;
        float:left;
    }
    
    #responsive-tiles-container{
        overflow: auto;
    }

The second ruleset in this sample helps to prevent the 'collapsed div' phenomenon.

Collapsed Elements

I must warn you that floating elements can make you crazy because there are some strange side affects that can come with them. One of the problems of using floats is dealing with the 'collapsed div' phenomenon. Here's an example that demonstrates it in a way that you can see it when you view the page in the browser:

<div id="collapsed-div">
        hello!
        <div class="tile">x</div>
    </div>

By putting a border around the parent div above (with the ID of 'collapsed-div') you'll see what happens to it when a child element is floated:

#collapsed-div{
        background-color:lightsalmon;
    }

You can see that when you float an element, it can mess up the default flow of block-level elements which is to stack vertically. The parent element doesn't stretch out vertically to accomodate the floated child. There are a few 'hacks' for fixing this problem, one of them is to set the overflow property to 'auto' on parent of the floated element. But this solution may have side effects of its, depending on how your page is set up. The solution that seems to be the most common is known as the 'clear fix' hack. You can apply this CSS to the parent element to 'clear' the float:

.clearfix::after {
      content: "";
      display: table;
      clear: both;
    }

The details of this CSS code is a little too advanced for us at this point, I just want to make you aware of the problem that floating elements can cause, and a solution for dealing with it. But for now, you can apply the clearfix hack by adding a class attribute to the collapsed div, like so:

<div id="collapsed-div" class="clearfix">
    hello!
    <div class="tile">x</div>
</div>

Creating a Column Strategy

One common tactic is to create rulesets that float elements and use various percent widths that can be used in combination to total 100%. The rulesets look something like these (you probably wouldn't set the background-color in them, I just did that to help you see the boundaries):

.col-25{ float:left; width:25%; background-color: lightgray; }
    .col-33{ float:left; width:33.33%; background-color: darkgray; }
    .col-40{ float:left; width:40%; background-color: gray; }
    .col-60{ float:left; width:60%; background-color: gainsboro; }
    .col-75{ float:left; width:75%; background-color: black; }
    
    #col-container div{ color:white; padding: 10px 0px; text-align: center; margin-bottom: 8px; }

Notice that the 'col' rulesets use class selectors so that they can be applied to any element. You might apply these rulesets to HTML code that looks like this:

<div id="col-container">
        <!-- First Row-->
        <div class="col-25">25</div>
        <div class="col-75">75 </div>
        <!-- Second Row-->
        <div class="col-40">40</div>
        <div class="col-60">60</div>
        <!-- Third Row-->
        <div class="col-33">33</div>
        <div class="col-33">33</div>
        <div class="col-33">33</div>
    </div>

This example is a bit simplified, and if you were to use it as is you might run into a problematic side-effect of floating elements known as the 'collapsed div phenomenon'. We'll talk about this problem, and how to fix it later in this lesson.

You could wrap each group of columns inside of an element that applies the clearfix to avoid the collapsed div issue. In the example below, I've updated a few rows of columns from a previous example by placing each one in a div with a CLASS attribute of 'row':

<div id="col-container">
        <div class="clearfix">
            <div class="col-25">25</div>
            <div class="col-75">75 </div>
        </div>
        <div class="clearfix">
            <div class="col-40">40</div>
            <div class="col-60">60</div>
        </div>
        <div class="clearfix">
            <div class="col-33">33</div>
            <div class="col-33">33</div>
            <div class="col-33">33</div>
        </div>
    </div>

Luckily, there are other ways of dealing with layouts that have emerged in CSS. If you are interested, you can google 'flexbox' and 'css grids'. But for now, we'll just focus floating elements.

NEXT LESSON: Creating Responsive Web Pages With CSS Media Queries