CSS float

The CSS float property is used to define where the element should float. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .one{float: left;}
      .two{float: right;}
   </style>
</head>
<body>

   <div class="one">float: left</div>
   <div class="two">float: right</div>

</body>
</html>
Output
float: left
float: right

Note - If the position: absolute is defined to an element, then float property will not be applied to it. Or simply we can say that the float property has no effect on an absolutely positioned element.

CSS float Syntax

The syntax of float property in CSS, is:

float: x;

The value of x should be any of the following:

CSS float Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .a{float: left; background-color: purple; color: white; padding: 12px;}
      .b{float: right; background-color: purple; color: white; padding: 12px;}
      .c{float: none; background-color: green; color: white; padding: 12px;}
   </style>
</head>
<body>

   <div class="a">float: left</div>
   <div class="b">float: right</div>
   <div class="c">float: none</div>

</body>
</html>
Output
float: left
float: right
float: none

Note - Define clear property to an element that is available right after the element with float property defined to it, to avoid floating of element around it. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .a{float: left; background-color: purple; color: white; padding: 12px;}
      .b{background-color: green; color: white; padding: 12px;}

      .c{float: left; background-color: purple; color: white; padding: 12px;}
      .d{clear: left; background-color: green; color: white; padding: 12px;}
   </style>
</head>
<body>

   <div class="a">float: left</div>
   <div class="b">Without clear</div>

   <br/>

   <div class="c">float: left</div>
   <div class="d">With clear: left</div>

</body>
</html>
Output
float: left
Without clear

float: left
With clear: left

Let me create one more example on the same concept as of above example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .a{float: right; background-color: purple; color: white; padding: 12px;}
      .b{background-color: green; color: white; padding: 12px;}

      .c{float: right; background-color: purple; color: white; padding: 12px;}
      .d{clear: right; background-color: green; color: white; padding: 12px;}
   </style>
</head>
<body>

   <div class="a">float: right</div>
   <div class="b">Without clear</div>

   <br/>

   <div class="c">float: right</div>
   <div class="d">With clear: right</div>

</body>
</html>
Output
float: right
Without clear

float: right
With clear: right

CSS Online Test


« Previous Tutorial Next Tutorial »