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?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ 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

Ad