我有一個頁面在水平和垂直方向上溢出視口,並且我想貼上導航,以便它始終位於頂部並水平居中。
現在,我可以讓黏性頂部工作,但居中不起作用。有人可以幫忙嗎?
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