【发布时间】:2018-01-25 05:36:21
【问题描述】:
通过像这样设置body 元素的样式来获得具有单一背景颜色的居中、最大宽度的网站是微不足道的:
body {
max-width: 500px;
margin: auto;
background-color: black;
}
header {
height: 100px; /* Might not be static */
background-color: red;
}
#main {
height: 300px; /* Might not be static */
background-color: yellow;
}
footer {
height: 200px; /* Might not be static */
background-color: blue;
}
<header>
</header>
<section id="main">
</section>
<footer>
</footer>
但是,如果您希望页面的每个部分的背景颜色 在任一侧无限延伸,那么事情很快就会变得非语义:
header {
height: 100px; /* Might not be static */
background-color: red;
}
#main {
height: 300px; /* Might not be static */
background-color: yellow;
}
footer {
height: 200px; /* Might not be static */
background-color: blue;
}
.container {
box-sizing: border-box;
margin: auto;
max-width: 500px;
height: 100%;
border: 2px black dotted;
}
<header>
<div class="container">
</div>
</header>
<section id="main">
<div class="container">
</div>
</section>
<footer>
<div class="container">
</div>
</footer>
有没有什么好的方法可以在不给每个顶层块添加容器div的情况下实现第二个例子的效果?即使是动态生成此类容器的 CSS 技巧也会更可取。
【问题讨论】:
-
您能否发布您想要获得的最终布局,例如背景栏是否要在 500 像素居中的容器之外展开?
-
第二个 sn-p 是最终布局的近似值。问题指出,目标是为页面内容设置最大宽度,每个顶级块的背景无限延伸到任一侧 - 不使用容器。
-
行的高度是否像您的示例中一样?
-
@Constantin,
已被弃用 20 年。 w3.org/TR/html4/present/graphics.html#edef-CENTER -
我还在用它;)