HTML – CSS Float – Float basics

When you float an element it becomes a block box. This box can then be shifted to the left or right on the current line.

The markup options are “float: left”, “float: right” or “float: none”.

A floated box is laid out according to the normal flow, then taken out of the flow and shifted to the left or right as far as possible. Content can flow down the right side of a left-floated box and down the left side of a right-floated box.

You can also put several floats beside each other.

Where will a floated element move to?

Floated boxes will move to the left or right until their outer edge touches the containing block edge or the outer edge of another float.

If there isn’t enough horizontal room on the current line for the floated box, it will move downward, line by line, until a line has room for it.

Do floated items need a width?

You should always set a width on floated items (except if applied directly to an image – which has implicit width). W3C’s Cascading Style Sheets, level 2, CSS2 Specifications states:

“A floated box must have an explicit width…”

If no width is set, the results can be unpredictable. Theoretically, a floated element with an undefined width should shrink to the widest element within it. This could be a word, a sentence or even a single character – and results can vary from browser to browser.

Elements above and below floated elements

Block level elements above a floated element will not be affected by it. However, elements below will wrap around the floated element:

Borders, background images and background color

While content will wrap around a floated element, border, background image and background color will extend underneath.

If you do not want elements below a floated element to wrap around it, you can apply the clear property to the following element using “clear: left”, “clear: right” or “clear: both”.

For every div containing one or more floated divs, you can assign a label (i.e. “clearfix”) and assign CSS code to clear floats:

HTML:

<div class="container clearfix">
  <div id="content"></div>
  <div id="sidebar"></div>
</div>

CSS:

.clearfix:after {
    clear: both;
    content: " ";
    display: block;
    height: 0;
    max-height: 0;
    overflow: hidden;
    visibility: hidden;
}

Note: “:after” and “:before” are pseudo elements which allow you to insert content onto a page from CSS (without it needing to be in the HTML).

 

Next we need to learn how to create equal column height using CSS.

HTML – CSS Float – Float basics was last modified: May 26th, 2015 by tabcom