Maison > Questions et réponses > le corps du texte
J'ai une page qui déborde de la fenêtre d'affichage à la fois horizontalement et verticalement, et je souhaite coller la navigation pour qu'elle soit toujours en haut et centrée horizontalement.
Maintenant, je peux faire fonctionner le dessus collant, mais pas le centrage. Quelqu'un peut-il m'aider ?
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
Contrairement à la position : positionnement collant et vertical, left: 50%
n'est pas une option de positionnement dynamique, elle définit simplement la position initiale ; La barre de défilement horizontale la fait toujours bouger afin qu'elle reste "à 50 % du bord gauche".
Pour obtenir un positionnement fixe à gauche et à droite, ajoutez une marge avec position:fixed
的标题容器,在其中,标题 div 可以获得 auto
autour du titre :
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
Après quelques recherches, j'ai trouvé ceci :
Essentiellement, il ne collera pas car le corps s'étendra automatiquement jusqu'à atteindre la largeur d'une très grande boîte.
Le placer dans un conteneur de blocs en ligne empêchera la largeur de s'étendre automatiquement aux enfants, ce qui permettra un comportement de collage.
Donc ça marche :
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