8) Understanding Floats


Floats are used to rearrange how elements in a web page are displayed. For understanding floats you need to understand how a natural float looks like.

Block level element takes 100 % of the width and are aligned below each other in a sequence.

Inline element displayed within the line.

By using float property we can align elements to right or left of its container. This is a change to natural flow and the elements below the floated element can be deranged.

Let us discuss float property with an example.

By floating an image to the left the element following it will move up and flow next to element. If the content is longer than the image the remaining text will flow below it.

The main problem is all element below the floated element will flow around it as long there is a space.

So we will apply some CSS to it:

Edit this example here: https://jsfiddle.net/kritika90/x4j06w2j/

CSS Float

Clearing Floats:

To return natural page-flow floats must be cleared. In the above example if we want h1 not to float with the image we apply the clear property to h1. This will return it back to natural stacking flow.

Float also effects the parent element. The parent element will not recognize the height of floated element. If all the content within the parent element is floated then its height will become zero. When there is no element left in the parent element to clear the float parent element will have to self-clear.

Ways to Self-clear float:

Use Overflow property


Other use of Overflow:

Generally, overflow is used when a specific height is given to an element.

Overflow: hidden Will clip the content to height specified
overflow: auto add a scrollbar