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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Build modern and responsive webpages

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

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

More Front-end resources