我试图在这个例子中将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
使用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>
从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>
一个更简单的想法,没有计算的麻烦是使它足够大并隐藏溢出:
.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>