I have a page that overflows the viewport both horizontally and vertically, and I want to paste the navigation so that it is always on top and centered horizontally.
Now I can get the sticky top to work, but the centering doesn't. Can anyone help?
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
Unlike position:sticky and vertical positioning,
left: 50%
is not a dynamic positioning option; it just sets the initial position. Horizontal scrollbar still causes it to move so it stays "50% from left edge".To achieve fixed left and right positions, add a title container with
position:fixed
around the title, within which the title div can getauto
margins:After some digging, I found this:
Why doesn't my element stick to the left when using positional stickyness in CSS?
Essentially, it won't stick because the body will automatically expand to the width of a very large box.
Putting it inside an inline block container will prevent the width from automatically expanding to children, allowing for paste behavior.
So this works: