如何定位一些粘性的东西,使它垂直地跟随屏幕的中心



正如您在我的代码片段中看到的,通过使用top: 50%;,我几乎达到了我想要的效果。但并没有完全集中在屏幕上。如果我添加transform: translateY(-50%);,我确实实现了居中,但是现在红色div的位置太高了,并没有一直走到底部。有人有什么想法吗?

(也请注意,我不知道这个红色div的高度,因为它应该是一个图像,首先,其次,我需要它是响应的意思是高度会改变)

* {
margin: 0;
padding: 0;
}
.other_content {
height: 80vh;
width: 100%;
background-color: #eee;
}
section {
background-color: skyblue;
height: 300vh;
width: 100%;
position: relative;
}
.sticky {
position: sticky;
top: 50%;
/* transform: translateY(-50%); *//* DOES NOT WORK */
width: 90%;
margin-left: 5%;
background-color: red;
}
<div class="other_content"></div>
<section>
<div class="sticky">
<p>IMAGE WITH <br> UNKNOWN <br> HEIGHT <br> GOES HERE</p>
</div>
</section>
<div class="other_content"></div>

.sticky {
position: sticky;
top: 45%
/* transform: translateY(-50%); *//* DOES NOT WORK */
width: 90%;
margin-left: 5%;
background-color: red;
}

只需将顶部百分比从50%更改为45%;

如果我理解正确的话,你能把顶部改为40%使它更高吗?(应该)在中间完全对齐。

* {
margin: 0;
padding: 0;
}
.other_content {
height: 80vh;
width: 100%;
background-color: #eee;
}
section {
background-color: skyblue;
height: 300vh;
width: 100%;
position: relative;
}
.sticky {
position: sticky;
top: 45%;
/* transform: translateY(-50%); *//* DOES NOT WORK */
width: 90%;
margin-left: 5%;
background-color: red;
}
<div class="other_content"></div>
<section>
<div class="sticky">
<p>IMAGE WITH <br> UNKNOWN <br> HEIGHT <br> GOES HERE</p>
</div>
</section>
<div class="other_content"></div>

最新更新