HTML and CSS Reference
In-Depth Information
This works like a charm, except for one major drawback: the outer floated container may then need
clearing of its own if there is other content it might run into. Depending on your particular layout and
design, it might be as simple as adding
clear:both
to another element, or even to the container itself.
You can produce complex layouts by floating nearly every element on the page and applying
clear
properties where necessary, hopefully to an already meaningful element rather than resorting to
presentational markup. Overly complicated float-based layouts, with lots of elements floating in every
direction, can be problematic and fragile. They can also have problems in older browsers, especially
earlier versions of Internet Explorer.
Overflow
If floating the container isn't feasible, another option might be to apply an
overflow
property with a value
of either
hidden
or
auto
. The
overflow
property in CSS instructs a browser in how to deal with content
that is too big for its container. A block-level element with no declared width or height (the default state
being
width:auto
and
height:auto
) will automatically expand vertically to enclose its contents, and
expand horizontally to fill its container. If you declare your own explicit width or height to override that
standard rendering, the browser needs to know what to do with overflowing content. By default, the
content just runs out of its container and remains visible, like you see in Figure 9-12. Text wraps to fit
within the width (assuming the text has room to wrap), but it can overflow vertically beyond the specified
height, spilling out of the bottom of the box.
Figure 9-12.
Content is visible when it overflows its container
The CSS
overflow
property accepts the values
visible
(the default),
hidden
(overflowing content is
hidden beyond the edge of the container),
scroll
(adds scrollbars in both directions), or
auto
(overflowing content invokes scrollbars when necessary). But what does this have to do with floats?
There's an interesting side effect of altering an element's
overflow
property: applying a value of
hidden
or
auto
to an element containing floats will make that element expand around its floating children
(
overflow:scroll
has the same effect but also adds scrollbars, which you usually don't want to see). It's
as if the
overflow
property “reminds” the element that it should enclose its contents. Returning to our
example, we can set the overflow of the containing element and it will automatically clear the floats inside
it:
#content {
overflow: auto;
}