Clearing & Containing Floats
The
float
property was originally designed to allow content to wrap around images. An image could be floated, and all of the content surrounding that image could then naturally flow around it. Although this works great for images, the float
property was never actually intended to be used for layout and positioning purposes, and thus it comes with a few pitfalls.
One of those pitfalls is that occasionally the proper styles will not render on an element that it is sitting next to or is a parent element of a floated element. When an element is floated, it is taken out of the normal flow of the page, and, as a result, the styles of elements around that floated element can be negatively impacted.
Often
margin
and padding
property values aren’t interpreted correctly, causing them to blend into the floated element; other properties can be affected, too.
Another pitfall is that sometimes unwanted content begins to wrap around a floated element. Removing an element from the flow of the document allows all the elements around the floated element to wrap and consume any available space around the floated element, which is often undesired.
With our previous two-column example, after we floated the
<section>
and <aside>
elements, and before we set a width property value on either of them, the content within the <footer>
element would have wrapped in between the two floated elements above it, filling in any available space. Consequently, the <footer>
element would have sat in the gutter between the <section>
and <aside>
elements, consuming the available space.Layout without Cleared or Contained Floats Demo
To prevent content from wrapping around floated elements, we need to clear, or contain, those floats and return the page to its normal flow. We’ll proceed by looking at how to clear floats, and then we’ll take a look at how to contain floats.
Clearing Floats
Clearing floats is accomplished using the
clear
property, which accepts a few different values: the most commonly used values being left
, right
, and both
.1 2 3 4 | div { clear: left; } |
The
left
value will clear left floats, while the right
value will clear right floats. Theboth
value, however, will clear both left and right floats and is often the most ideal value.
Going back to our previous example, if we use the
clear
property with the value ofboth
on the <footer>
element, we are able to clear the floats. It is important that this clear be applied to an element appearing after the floated elements, not before, to return the page to its normal flow.1 2 3 4 | footer { clear: both; } |
No comments:
Post a Comment