CSS float – floating left, right and clearing

CSS float property decides if an element should float left or right. It can take two value – float:left or float:right. Elements after a floating element will also float around it. To clear float clear property can be used (clear:both, clear:left or clear:right).

Here are some examples.

Float left and right example with clear

This example has one left floating and one right floating div. One empty div with clear:both. Then it has one h2 which will not float.

<style type="text/css">
.left {
  float:left;
  width:50px; height:50px;
  background-color:lightgreen;
}
.right {
  float: right;
  width:50px; height:50px;
  background-color:lightgreen;
}
.clearboth {clear:both;}
</style>
<div class="left">
left
</div>
<div class="right">
right
</div>
<div class="clearboth"></div>
<h2>this is h1</h2>
refresh

Float left and right example without clear

This example has one left floating and one right floating div. Then it has one h2 which will also float. In case we want it to not float, we need to apply clear:both on it or some other element before it.

<style type="text/css">
.left {
  float:left;
  width:50px; height:50px;
  background-color:lightgreen;
}
.right {
  float: right;
  width:50px; height:50px;
  background-color:lightgreen;
}
</style>
<div class="left">
left
</div>
<div class="right">
right
</div>
<h2>this is h1</h2>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments