我有一个简单的HTML文档,其中包含height
的100vh
。该元素包含标题。现在当我滚动时没有按预期发生。我需要的是一个效果,页面保持不变,我的标题向上滚动并退出视口。我怎样才能做到这一点?
我的代码简化了:
html,
body {
margin: 0;
padding: 0;
}
#wrapper {
background-color: red;
height: 100vh;
width: 100%;
}
h1 {
color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div id="wrapper">
<h1>Title</h1>
</div>
您可以采用相反的方式 - 不修复要滚动的元素,而是使用负z-index放入后台的contents元素:
将position:fixed
应用于包装器并使用z-index: -1
将其移至背景。从position: absolute
中删除h1
以将其位置重置为static
以允许其滚动。
要使滚动成为可能,您需要为title元素(至少150%或更多)提供足够的高度,或者之后跟随的另一个(可能不可见)元素,如下面的示例所示。
h1
内部的文本可以通过flex完成(见下文)。
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
#wrapper {
position: fixed;
z-index: -1;
background-color: red;
height: 100vh;
width: 100%;
}
h1 {
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100%;
margin: 0;
}
.something_else {
height: 100%;
}
<div id="wrapper"> wrapper contents here... </div>
<h1>Title</h1>
<div class="something_else"></div>