gpt4 book ai didi

html - 使用 "position: sticky"使元素始终显示在屏幕上

转载 作者:可可西里 更新时间:2023-11-01 13:25:43 24 4
gpt4 key购买 nike

我有一个已知高度的容器(高度有时比屏幕长)。

这个容器有一个垂直和水平居中的元素(通过 flex)。

我希望让这个元素始终在屏幕上垂直居中在容器可见部分的 block 中。

我尝试过的:

  • 位置:粘性; top:50% - 然而这只会使它保持在容器的下半部分的中心。
  • 位置:粘性; bottom:50% - 然而这只会使它保持在上半部分的中心
  • 位置:粘性;顶部:50%; bottom:50%; - 似乎 top 覆盖了 bottom 所以这就像我第一次尝试仅使用 top:50%
  • 我试过设置负值,但没用

这是一个演示:

.container {
height: 1200px;
background-color: rgba(0, 0, 0, .7);
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.center-piece {
background-color: green;
position: sticky;
top: 50%;
}
.center-piece2 {
background-color: steelblue;
position: sticky;
bottom: 50%;
}
<div class="container">
<div class="center-piece">
#1
</div>
<div class="center-piece2">
#2
</div>
</div>

有没有办法让它在容器的可见部分(顶部和底部)“始终显示在屏幕上”时完美居中?

这是我的应用程序的截屏视频:https://www.youtube.com/watch?v=CwYaBgolNHU

“rawr”将是其背后图像的控件。

最佳答案

我可能误解了你的问题,但你可以使用:

position: fixed;
top: 50vh;

?

.container {
height: 1200px;
background-color: rgba(0, 0, 0, .7);
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.center-piece {
background-color: green;
position: fixed;
top: 50vh;
left: 50vw;
transform: translate(-50%,50%);
}
<div class="container">
<div class="center-piece">#1</div>
</div>

关于html - 使用 "position: sticky"使元素始终显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38812478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com