我有一个页面在水平和垂直方向上溢出视口,并且我想粘贴导航,以便它始终位于顶部并水平居中。
现在,我可以让粘性顶部工作,但居中不起作用。有人可以帮忙吗?
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;
}
I should always be at the top and centeredI am extremely large and wide
CodePen:https://codepen.io/hbchin/pen/bGjpQLJ
Copyright 2014-2026 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; }