拉伸::在元素之前到屏幕的宽度

问题描述 投票:1回答:3

我试图在这个例子中将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链接:https://codepen.io/anon/pen/yZGzPO

期望的结果应如下所示:enter image description here

html css css-position pseudo-element css-calc
3个回答
2
投票

使用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>

1
投票

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>

1
投票

一个更简单的想法,没有计算的麻烦是使它足够大并隐藏溢出:

.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>
© www.soinside.com 2019 - 2024. All rights reserved.