通过设置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>
&#13;
但是,如果您希望页面的每个部分的背景颜色在任何一侧无限延伸,那么事情很快就会变得非语义:
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;
}
&#13;
<header>
<div class="container">
</div>
</header>
<section id="main">
<div class="container">
</div>
</section>
<footer>
<div class="container">
</div>
</footer>
&#13;
有没有一种很好的方法来实现第二个例子的效果而不向每个顶级块添加容器div?即使是动态生成此类容器的CSS技巧也是可取的。
答案 0 :(得分:1)
header {
height: 100px;
/* Might not be static */
background-color: red;
position: relative;
}
#main {
height: 300px;
/* Might not be static */
background-color: yellow;
position: relative;
}
footer {
height: 200px;
/* Might not be static */
background-color: blue;
position: relative;
}
footer,
header,
#main {
box-sizing: border-box;
margin: auto;
max-width: 500px;
border: 2px black dotted;
}
header:before,
#main:before,
footer:before {
content: '';
width: 100vw;
transform: translate(-50%);
height: 100%;
left: 50%;
position: absolute;
z-index: -1;
}
header:before {
background-color: red;
}
#main:before {
background-color: yellow;
}
footer:before {
background-color: blue;
}
&#13;
<header>
My header so nice;
</header>
<section id="main">
my content so nice
</section>
<footer>
my footer very low
</footer>
&#13;