The Float Property

The float property allows a block element to float to the left or right of its container without creating a break before and after it.

Below are a few examples showing the effects of using float. They are based on the following HTML.

<div id="div1">div</div>
<p>p with some text</p>
<div id="div2">div</div>

First lets start with an example that does not use the float or display properties. The 3 elements (div, p, div) are block elements and are rendered vertically.

div

p with some text

div

When we change the display property to inline-block they are displayed horizontally.

div

p with some text

div

 

div, p {
    display: inline-block;
}

This same effect can be made by adding float:left to each element and removing the display property.

div

p with some text

div

 

 div, p { 
    float: left; 
}

We can also float the first two elements left and the second div to the right.

div

p with some text

div

 

#div1, p {
    float: left;
}
#div2 {
    float: right;
}

Look what happens when we float the last two elements to the right.  The first HTML element in the source code (p) is floated to the right hand side of the container, then the second div is floated as far right as it can be, which positions it to the left of the p element.

div

p with some text

div

 

#div1 {
    float: left;
}
#div2, p {
    float: right;
}

Without changing the order of the HTML elements, we can position the last two elements to the right (in the original order) by setting the two elements to inline-block, wrapping them in a div, and floating that wrapper div to the right.

div

p with some text

div

 

<div id="div1">div</div> 
<div id="wrapper">
    <p>p with some text</p>
    <div id="div2">div</div>
</div>
#div1 {
    float: left;
}
#wrapper {
    float: right;
}
p, #div2 {
    display: inline-block;
}

Clearing Floats

Consider the following example. Here we have three p elements. The first two are floated left and the third element does not have the float property set. Even though the third element doesn’t float, the float property on the second element prevents a break between the second and third element. Possibly, not what was intended.

paragraph 1

paragraph 2

paragraph 3

 

If we want the third element to be displayed under the two floated elements, we can suppress the the effects of the second p element on the third p element using the clear property.

paragraph 1

paragraph 2

paragraph 3

 

There are three values for clear: left, right, and both. Left suppresses the effects of any float on the left, right suppresses the effects of any float on the right, and both suppresses the effects of any floats on the left and right.

© 2018, Eric. All rights reserved.