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.

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

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

Ad