CSS Float & Clear Property – Move to left or right side

CSS

0 Comments

The float property allows you to move an element to the left or right side of its container.

And the clear property allows other elements to avoid being placed next to floated elements (more details after the example).

Example

HTML

<div class="box float-left">float left</div>
<div class="box float-right">float right</div>

<p class="clear-none">
	Clear is set to none. Clear is set to none. Clear is set to none.
	Clear is set to none. Clear is set to none.
</p>

<p class="clear-right">clear right</p>
<p class="clear-left">clear left</p>
<p class="clear-both">clear both</p>

CSS

.box {
    width: 50px;
    height: 150px;
    background-color: lightblue;
}

p {
    border: 2px solid darkred;
}

.float-right {
    float: right;
    height: 75px;
}

.float-left { float: left; }
.clear-none { clear: none; }
.clear-right { clear: right; }
.clear-left { clear: left; }
.clear-both { clear: both; }

Result

float: left (or right)
As you can see from the example above, this moves an element to the left or right side of its container. Other elements (like paragraphs) will flow around the floated elements by default.
clear: both
This causes an element to be placed under all floated elements that are near it (instead of being placed next to them).
clear: right
This works the same as clear: both, except it only avoids floats on its right side. You can see this in the example. The box labeled "clear right" is placed under the "float right" box. However, it doesn't mind being placed next to the box labeled "float left".
clear: left
Works exactly as you'd expect.
clear: none (the default)
Don't avoid being placed next to floated elements. Elements styled this way can be on the same line as floats and will flow around them if there isn't enough room. Look at the first line of the example for a good demonstration of what this does. This is the default if you don't set clear to anything.
Practice in Editor

Leave a Comment