CSS Float

The float property enables you to take an element out of normal flow and put content side-by-side. Elements are floated horizontally , that means, an element can only be floated left or right only.

Float property accepts keyword values left and right float elements those directions respectively and set to none for not floated. When you set the float property for an element , you should specify the width and height otherwise its sizing becomes shrink-to-fit horizontally and vertically.

Consider the following example:

When you run this code on browser you will get the folowing output:

CSS float

In the above picture the boxes are not set the float property.

Now we set the float property to both boxes as float:left;

In the above code we set float property to each box as float:left;

Now you can see the boxes floated from left to right.

CSS float left

Again we set first box as float:left and second box as float:right;


CSS float right

Now you can see first box is floted to left and second one is floated to right.


The clear property is used to control the flow of floating content. It actually cancel the effects of the float property. Clear property accepts keyword values left and right for clear elements those directions respectively and set the property both for clear both sides.



CSS clear

In the above code we set float property to right for both Box1 and Box2 . So the Box3 occupy the left end space and Box1 and Box2 floatedon right side.

Again we set the clear property to Box3 as clear:right;


CSS clear right

Now you can see the Box1 and Box2 floated on extreme right and Box3 is placed on the next level. Here Box3 clear the float property of the above two boxes, so it placed on the next line. If you set clear:both; will clear the left and right property of the float element.


While overlapping CSS elements, when using absolute and relative position, the default behavior is to have the first elements underneath later ones. In these cases we can control layering of positioned elements by using the z-index property . When using the z-index property you can specify which of the boxes appears on top the other one.


CSS z-index

Now you can see the BOX-1 is behind the BOX-2, because z-index of BOX-1 is 1 and BOX-2 is 2. Now we are going to change the z-index order as BOX-1 is 2 and BOX-2 is 1.


CSS z-index order

Now you can see BOX-1 come in front and BOX-2 going behind the BOX-1.

It is noted that z-index works on positioned elements only like position:absolute, position:relative and position:fixed.