pet*_*tsk 2 html css css-position pseudo-element css-calc
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;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<header>Header</header>
<main>Main content</main>
</div>Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<header>Header</header>
<main>Main content</main>
</div>Run Code Online (Sandbox Code Playgroud)