将 ::before 元素拉伸到屏幕宽度

Stretching ::before element to width of screen

在此示例中,我试图将 header::before 伪元素拉伸到整个页面宽度。

100vw 给伪元素屏幕的宽度,到目前为止一切顺利。

但是左侧位置 left: -100%; 将伪元素推到左侧太远。是否可以计算出正确的左侧位置?

.wrapper {
  width: 70%;
  max-width: 800px;
  margin: 0 auto;
}

header {
  background: pink;
  position: relative;
  z-index: 0;
}

header::before {
  background: lightblue;
  position: absolute;
  z-index: -1;
  content: "";
  height: 100%;
  width: 100vw;
  /* full page width */
  left: -100%;
  /* left positioning */
}

main {
  background: wheat;
}
<div class="wrapper">
  <header>Header</header>
  <main>Main content</main>
</div>

Codepen link: https://codepen.io/anon/pen/yZGzPO

期望的结果应该是这样的:

根据 left:calc(50% + -50vw) 制作那个伪元素位置,你就完成了!

.wrapper {
 width: 70%;
 max-width: 800px;
 margin: 0 auto;
}

header {
 background: pink;
 position: relative;
 z-index: 0;
}

header::before {
 position: absolute;
 background: lightblue;
 content: "";
 z-index: -1;
 width: 100vw;
 height: 100%;
 left: calc(50% + -50vw);
}

main {
 background: wheat;
}
<div class="wrapper">
 <header>Header</header>
 <main>Main content</main>
</div>

使用 left: calc(-50vw + 50%) 将其放置在整个 视口 宽度上。

当您使用 margin: 0 auto 时,它 居中 header 包装内。这意味着 header 两侧的 空格 的宽度是 100vw 减去 header 的宽度。那将是来自 元素的 100vw - 100%,因此视口将从 -(100vw - 100%) / 2.

开始

参见下面的演示:

.wrapper {
  width: 70%;
  max-width: 800px;
  margin: 0 auto;
}

header {
  background: pink;
  position: relative;
  z-index: 0;
}

header::before {
  background: lightblue;
  position: absolute;
  z-index: -1;
  content: "";
  height: 100%;
  width: 100vw; /* full page width */
  left: calc(-50vw + 50%); /* left positioning */
}

main {
  background: wheat;
}
<div class="wrapper">
  <header>Header</header>
  <main>Main content</main>
</div>

一个不费心计算的更简单的想法是让它足够大并隐藏溢出:

.wrapper {
  width: 70%;
  max-width: 800px;
  margin: 0 auto;
}

header {
  background: pink;
  position: relative;
  z-index: 0;
}

header::before {
  content: "";
  background: lightblue;
  position: absolute;
  z-index: -1;
  top:0;
  bottom:0;
  left: -100vw;
  right:-100vw;
}

main {
  background: wheat;
}

body {
 overflow-x:hidden;
}
<div class="wrapper">
  <header>Header</header>
  <main>Main content</main>
</div>