search

Home  >  Q&A  >  body text

Make elements stick to the top and center

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粉301523298P粉301523298255 days ago269

reply all(2)I'll reply

  • P粉064448449

    P粉0644484492024-03-20 14:47:41

    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

    reply
    0
  • P粉668019339

    P粉6680193392024-03-20 14:41:23

    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

    reply
    0
  • Cancelreply