CSS – Float and clear

floating

To understand float and clear property of CSS we need understand CSS position. We have read all and know HTML tag or element link together with the bond. But by this property, we can prevent that bond. So we can say –

Removes elements from the document flow and moves them to a specified edge. Other content within the parent element will wrap around floats.

Floating based on these properties.

float: left / right / none

Stacking order

Floated elements stack up to the parent edge, then move down to the next available edge.
Take care with elements that have differing heights – the first available edge isn’t always below.


.ski {
	float: right;
}
.sled {
	float: left;
}


<article>
	<img class="img" src="img.jpg" alt="img!" />
	<img class="img" src="img.jpg" alt="img!" />
</article> 

Clearing Floats

The clearing is necessary if:

Floated items can be taller than non-floated content.
All children are floating.

Common float-clearing methods:

Clear with subsequent elements

Requires sequence to stay intact – breaks if things move
Background / border do not extend


img {
	float: left;
}

.intro {
	clear: both;
}


<div>
	<img src="img.jpg" alt="img!" />
	<p>To successfully img, simply do not fall.</p>
</div>
<div class="intro">
	<p>Whee!</p>
</div>

Manual clearing

Requires an empty element
Might not be necessary later


.clear {
	clear: both;
}


<div>
	<img src="img.jpg" alt="img!" />
	<p>To successfully img, simply do not fall.</p>
	<div class="clear"></div>
</div>

The clearfix


.group:before, .group:after {
	content: "";
	display: table;
}

.group:after {
	clear: both;
}
.group {
	zoom: 1; /* IE6&7 */
}


<div class="group">
	<img src="img.jpg" alt="img!" />
	<p>To successfully img, simply do not fall.</p>
</div>

You May Also Like

About the Author: Pankaj Bisht