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

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources