CSS Float

CSS

In this tutorial we will learn about CSS Float and Clear property.

Sample layout

In the following image we have 6 divs and we are going to change their positions.

We have the header and footer in blue.

Then we have the container in lightgray.

In side the container we have 4 more divs in orange, green, pink and yellow color.

HTML of the above layout is given below.

<div id="header">
	<p>id="header"</p>
</div>
<div id="container">
	<p>id="container"</p>
	<div id="div-1">
		<p>id="div-1"</p>
		<p>This is a sample paragraph.</p>
	</div>
	<div id="div-2">
		<p>id="div-2"</p>
		<p>This is a sample paragraph.</p>
	</div>
	<div id="div-3">
		<p>id="div-3"</p>
		<p>This is a sample paragraph.</p>
	</div>
	<div id="div-4">
		<p>id="div-4"</p>
		<p>This is a sample paragraph.</p>
	</div>
</div>
<div id="footer">
	<p>id="footer"</p>
</div>

float : left

When we want to push an element as far as possible to the left we set its float property to left.

When an element is set to float left then other elements wrap around its right.

In the following example we have set div-2 to float left.

#div-2 {
	float : left;
}

clear : left

If we want no element to float to left for a given element then we have to set the clear property to left.

In the above example we have set the float property of div-2 to left and we have set the clear property of div-3 to left. This will make div-3 appear below div-2.

#div-2 {
	float : left;
}

#div-3 {
	clear : left;
}

float : right

When we want to push an element as far as possible to the right we set its float property to right.

When an element is set to float right then other elements wrap around its left.

In the following example we have set div-2 to float right.

#div-2 {
	float : right;
}

clear : right

If we want no element to float to right for a given element then we have to set the clear property to right.

In the above example we have set the float property of div-2 to right and we have set the clear property of div-3 to right. This will make div-3 appear below div-2.

#div-2 {
	float : right;
}

#div-3 {
	clear : right;
}

clear : both

If we want no element to float both on the left and right side of an element then we set its clear property to both.

In the following example we have set div-1 to float left and div-3 to float right and have set div-2 to clear both.

#div-1 {
	float : left;
}

#div-2 : {
	clear : both;
}

#div-3 : {
	float : right;
}

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT