skip to Main Content

I’m wondering if it’s possible, even though I’ve set my element to be fixed, with a top: 0 position, can I center it, or does it require a left position as well?

header {
  position: fixed;
  top: 0;
  width: 100%;
  background-color: yellow;
  max-width: 200px;
  margin: 0 auto;
}
  <header>
    <h1>Content</h1>
  </header>

3

Answers


  1. I think the problem is that you are setting position to fixed. Wrap your element in a container with fixed position and set the element position to relative, with margin: auto (1)

    header {
      margin: auto;
      position: relative;
      top: 0;
      width: 100%;
      background-color: yellow;
      max-width: 200px;
      margin: 0 auto;
    }
    
    .full-width: {
      position: fixed;
      width: 100%;
    }
    <div class=full-width>
      <header>
        <h1>Content</h1>
      </header>
    </div>
    Login or Signup to reply.
  2. Yes, you can center a fixed-position element horizontally using the margin: 0 auto; technique, even if it has a top: 0; position. This will center the element within its containing block (usually the viewport) along the horizontal axis.

    In your example, the <header> element will be fixed to the top of the viewport (top: 0;) and centered horizontally (margin: 0 auto;). Here’s the corrected CSS:

    header {
      position: fixed;
      top: 0;
      width: 100%;
      background-color: yellow;
      max-width: 200px;
      margin: 0 auto; /* Center horizontally */
    }
    

    This will center the <header> element horizontally within the viewport while keeping it fixed at the top. The max-width property will limit its width to 200 pixels.

    Login or Signup to reply.
  3. margin: 0 auto on a fixed element doesn’t work by itself. But by adding left and right as 0 it will. Also this snippet adds a text-align: center so the text is aligned within the element.

    header {
      position: fixed;
      top: 0;
      width: 100%;
      background-color: yellow;
      max-width: 200px;
      text-align: center;
      margin: 0 auto;
      left: 0;
      right: 0;
    }
    <header>header text</header>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search