【问题标题】:Bars of background color without container divs [duplicate]没有容器div的背景颜色条[重复]
【发布时间】: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
  • 我还在用它;)

标签: html css


【解决方案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;
}
<header>
  My header so nice;
</header>
<section id="main">
  my content so nice
</section>
<footer>
  my footer very low
</footer>

【讨论】:

  • 非常聪明!这可以通过将background-color: inherit; 添加到主:before 选择器来进一步改进,从而允许删除单个:before 规则。遗憾的是边框会在背景中产生间隙,但我的用例实际上并不需要边框。
猜你喜欢
  • 2020-05-13
  • 2014-10-27
  • 2018-05-04
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多