Floats are a fundamental element in building CSS-based websites and can be used to align images and build layouts and columns. If you recall how to align elements left and right in HTML, floating works in a similar way.

According to HTML Dog, the float property “specifies whether a fixed-width box should float, shifting it to the right or left, with surrounding content flowing around it.”

2_a

The float: left value aligns elements to the left and can also be used as a solid container to create layouts and columns. Let’s look at a practical situation in which you can use float: left.

2_b

The float: right value aligns elements to the right, with surrounding elements flowing to the left.

Quick tip: Because block elements typically span 100% of their parent container’s width, floating an element to the right knocks it down to the next line. This also applies to plain text that runs next to it because the floated element cannot squeeze in the same line.

2_c

You can correct this issue in one of two ways:

1. Reverse the order of the HTML markup so that you call the floated element first, and the neighboring element second.

2_c1

2. Specify an exact width for the neighboring element so that when the two elements sit side by side, their combined width is less than or equal to the width of their parent container.

2_c2

Internet Explorer 6 (IE6) has been known to double a floated element’s margin. So, what you originally specified as a 5-pixel margin becomes 10 pixels in IE6.

upd_2_d

A simple trick to get around this bug is to add display: inline to your floated element, like so:

Quick tip: have you ever had a parent element that did not fully wrap around its child element? You can fix this by making the parent container a floated element.

In some cases, though, floating left or right is not a workable solution — for example, if you want to center-align the container or do not want to specify an exact width. In this case, use overflow: hidden on your parent container to completely wrap any floated child elements within it.

6_b

(Visited 3 times, 1 visits today)