Make elements stick to the top and center
P粉301523298
P粉301523298 2024-03-19 17:30:43
0
2
297

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 am extremely large and wide

CodePen: https://codepen.io/hbchin/pen/bGjpQLJ

P粉301523298
P粉301523298

reply all(2)
P粉064448449

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 get auto margins:

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 am extremely large and wide
P粉668019339

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:

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 am extremely large and wide
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template