我有一个页面在水平和垂直方向上溢出视口,并且我想粘贴导航,以便它始终位于顶部并水平居中。
现在,我可以让粘性顶部工作,但居中不起作用。有人可以帮忙吗?
body {
text-align: center;
}
#header {
background-color: yellow;
width: max-content;
position: sticky;
top: 0;
left: 50%;
translate: -50%
}
#container {
background-color: black;
color: white;
width: 200vw;
height: 200vh;
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
}
<div id="header"> I should always be at the top and centered </div> <div id="container"> <span> I am extremely large and wide </span> </div>
CodePen:https://codepen.io/hbchin/pen/bGjpQLJ
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
与position:粘性和垂直定位不同,
left: 50%不是动态定位选项;它只是设置初始位置。水平滚动条仍然会导致它移动,因此它保持“距左边缘 50%”。要实现固定的左右位置,请在标题周围添加一个带有
position:fixed的标题容器,在其中,标题 div 可以获得auto边距:body { text-align: center; max-width:100vw; overflow:scroll; } /*added*/ #headercontainer{ position:fixed; width:100vw; left:0; top:0; } #header { background-color: yellow; width: max-content; /*left: 50%;*/ /*Removed*/ margin:auto;/*added*/ } #container { background-color: black; color: white; width: 200vw; height: 200vh; display: flex; justify-content: center; align-content: center; flex-direction: column; }经过一番挖掘后,我发现了这个:
为什么在CSS中使用位置粘性时我的元素不粘在左边?
本质上,它不会粘住,因为主体会自动扩展到非常大的盒子的宽度。
将其放入内联块容器中将使宽度不会自动扩展到子级,从而允许粘贴行为。
所以这有效:
body { text-align: center; } #header { background-color: yellow; width: max-content; position: sticky; top: 0; left: 50%; translate: -50% } #container { background-color: black; color: white; width: 200vw; height: 200vh; display: flex; justify-content: center; align-content: center; flex-direction: column; } #whole-thing { display: inline-block; }