使用固定宽度的侧栏,实际上非常简单。您将要使用浮点数,并且可能需要使用faux columns 技巧,具体取决于您的特定设计需求。
你会想要一些类似的东西:
<div class="left"></div>
<div class="right"></div>
<div class="middle">Content</div>
和:
div {
/* border-box, to make sure "width" is our intended width */
-moz-box-sizing: border-box; /* Firefox still uses prefix */
box-sizing: border-box;
}
.left {
float: left;
width: 100px;
background: #f00;
}
.right {
float: right;
width: 100px;
background: #00f;
}
.middle {
width: 100%;
padding: 0 100px;
background: #ccc;
}
See it in action here(这没有假列效果,但应该给你一个起点)。如果您使用输出更改部分的宽度,您会看到列保持不变,而内容保持在外部列的范围内。
内容列需要放在最后,因为它仍在文档流中,所以右列将在内容下方结束。
或者,您可以在侧栏上使用position: absolute;,如下所示:
.wrapper {
position: relative; /* Constrains the columns within their parent. Not needed if parent is <body> */
}
.left {
position: absolute;
top: 0;
left: 0;
}
.right {
position: absolute;
top: 0;
right: 0;
}
.middle {
padding: 0 100px;
}
div {
-moz-box-sizing: border-box;
box-sizing: border-box;
}
这些技巧适用于 IE8+、Firefox、Chrome、Safari 和 Opera。 IE7 可能会因为使用 W3C 框模型(“内容框”)而不识别 box-sizing CSS 而出现问题,但 there are a few tricks 可能会在您需要时使其工作。 IE6 应该没问题,因为它默认使用基于“border-box”的盒子模型。 (您可能需要使用z-index 来让IE 正常运行。如果是这样,则设置.middle{ position: relative; z-index: 1} 并将z-index: 2 添加到左右列。)
position: absolute 技巧确实比浮动技巧具有优势,因为您的侧边栏可以出现在内容 div 之前或之后,这使其成为可能更具语义的选项。
这些工作的原因是因为 a) 您的侧列是固定的,所以我们只需将填充设置为这些列的宽度,并且 b)position: absolute 和 float: [left/right] 将元素从文档流中取出,这意味着就文档而言,它们不存在并且不占用空间。这允许其他元素移动到这些元素曾经所在的位置,将它们叠加在一起。