我有一个页面在水平和垂直方向上溢出视口,并且我想粘贴导航,以便它始终位于顶部并水平居中。
现在,我可以让粘性顶部工作,但居中不起作用。有人可以帮忙吗?
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
P粉0644484492024-03-20 14:47:41
与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; }
I should always be at the top and centeredI am extremely large and wide
P粉6680193392024-03-20 14:41:23
经过一番挖掘后,我发现了这个:
本质上,它不会粘住,因为主体会自动扩展到非常大的盒子的宽度。
将其放入内联块容器中将使宽度不会自动扩展到子级,从而允许粘贴行为。
所以这有效:
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; }
I should always be at the top and centeredI am extremely large and wide