XML technologies / CSS / CSS Cookbook / Page layouts / Flexible multicolumn layouts with floats
(Excerpt from “CSS Kochbuch” by Christopher Schmitt)
Problem
Create a three-column layout whose column widths depend on the width of the browser window (see the following figure).
Figure: A three-column layout created with CSS.
Solution
First enclose the content in elements div. These have attributes id that, for demonstration purposes, refer to the elements’ positions within the page (see the next figure):
<div id="Kopfzeile">
[...]
</div>
<div id="linkeSpalte">
[...]
</div>
<div id="Hauptspalte">
[...]
</div>
<div id="rechteSpalte">
[...]
</div>
<div id="Fusszeile">
[...]
</div>Figure: The page’s default appearance.
Next define all three columns as floats aligned to the left. Make sure their widths are specified as percentages totaling 100% (see the next figure):
#rechteSpalte {
width: 33%;
float: left;
background: white;
padding-bottom: 1em;
}
#linkeSpalte {
width: 20%;
float: left;
background: white;
padding-bottom: 1em;
text-align: justify;
}
#Hauptspalte {
width: 47%;
float: left;
background: white;
padding-bottom: 1em;
}
#Fusszeile {
clear: both;
padding-bottom: 1em;
border-top: 1px solid #333;
text-align: center;
}Figure: If the main column is too wide, the right column moves below it.
Discussion
This method works because all columns are defined as left-aligned floats and together are no wider than 100%. Aligning the floats to the right reverses the columns, but otherwise produces the same result.
Make sure the elements within the columns have appropriate padding and margins, unless these are already accounted for in the column widths. Otherwise, the columns’ total width may exceed 100%, causing one or more columns to move below the others, as shown above. In addition, Internet Explorer for Windows through version 5.5 needs a separate width because of its box model bug (see the recipe Special values for Internet Explorer 5.x for Windows) if you use horizontal padding and borders for the elements div.
See also
The recipe Fixed-width multicolumn layouts using floats for creating fixed-width multicolumn layouts, and the article “NN4, 3 columns with Header and Footer” for information on creating a layout with two fixed-width columns and a third flexible-width column.
Copyright of the German edition © 2007 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “CSS Kochbuch” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln