Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Applying floats and clearfix to block elements

Name: float

Value: left | right | inherit | none

Char­ac­ter­is­tics :

  • Float­ing an ele­ment will cause it to move to the left-most or right-most edge of its par­ent container.
  • Float­ing removes the ele­ment from nor­mal doc­u­ment flow and changes the stack­ing context.
  • It will cause ele­ments below it to shift accordingly.

Iter­a­tion 1 : float: none; /* Default */

We have three col­ored square boxes, which are ren­dered accord­ing to the doc­u­ment flow and are stacked one after the other.

See the Pen float-1 by Kavit Shah (@kavitshah8) on Code­Pen.


Iter­a­tion 2 : float: right;

Float­ing the first red square to the right removes it from the doc­u­ment flow, hence the green square occu­pies the red square’s place as shown below.

See the Pen float-3 by Kavit Shah (@kavitshah8) on Code­Pen.


Iter­a­tion 3 : float: left;

Inter­est­ingly if we float the red square to left then it will over­lap the green square as shown below.

  • The floated ele­ment has the higher stack­ing con­text, hence it’s being ren­dered on top of the non-floated element.

See the Pen float-2 by Kavit Shah (@kavitshah8) on Code­Pen.


Iter­a­tion 4 : par­ent con­tainer collapsed

Apply­ing, float: left to all the squares cause the con­tainer to col­lapse. Hence, you can not see the white background.

  • As all the col­ored sqaure are floated they have the same stack­ing con­text and they are rel­a­tive to each other.

See the Pen float-4 by Kavit Shah (@kavitshah8) on Code­Pen.


Iter­a­tion 5 : pre­vent par­ent con­tainer col­lapsed using extra markup

We can add an extra an ele­ment, after all the floated squares and give it a style of clear:both as shown below. It will pre­vent the con­tainer from col­laps­ing. Hence, you can see the white background.

See the Pen float-5 by Kavit Shah (@kavitshah8) on Code­Pen.


Iter­a­tion 6 : pre­vent par­ent con­tainer col­lapsed using over­flow prop­erty on the container

We can add overflow:hidden, overflow:auto to the con­tainer ele­ment as shown below. It will pre­vent the con­tainer from col­laps­ing. Hence, you can see the white background.

See the Pen float-6 by Kavit Shah (@kavitshah8) on Code­Pen.


Check out James Williamson’s excel­lent tuto­r­ial on Clearfix !

Iter­a­tion 7 : pre­vent con­tainer col­lapsed using clearfix

clearfix is a tech­nique to pre­vent the con­tainer col­lapsed as shown below.

See the Pen float-7 by Kavit Shah (@kavitshah8) on Code­Pen.

Fur­ther read­ing about clearfix :

You may also like...