05. Floating Elements

Floating an element takes it out of its normal flow and places it to either the left or right of its containing box.

The floated element becomes block level. All the other elements are then set to flow around it.

Floating elements left and right

You can use float to stack elements right next to each other. However, it may be the case that you want an element to go to the next line. We can use the clear property to achieve this.

A value of left means that the left-hand side of the box should not touch any elements in the same container. A value of both means that neither left nor right should touch. Lastly, none means any side can be touched.

The code below floats all div elements to the left. A similar code is used to float the elements right.

div.float-left {
  border-radius: 5px;
  font-size: 4em;
  padding: 10px;
  float: left;
}

Floating elements to the left:

Floating elements to the right:

How to fix height of floating parent

Parents of floating elements may appear to have a height of 0. A workaround for this is to set the overflow property to auto, and the width to 100%.

Before the fix, the parent container (outlined by a solid black line) assumes a height of zero:

After applying an the above properties, the height of the containing div is now normal.

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Build modern and responsive webpages

HTML & CSS

Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Ad