0
votes

Below, I fixed a header to the top, set width: 100% and applied a margin to the body element of margin: 10%. I expected the header to remain at 100% width of the viewport, but instead it now has a left margin but reaches to the end of the viewport on the right side.

            * {
                box-sizing: border-box;
            }
            
            
        
            header {
                position: fixed;
                background-color: #59b1ff;
                top: 0;
                height: 20px;
                width: 100%;
            }
            
            body {
                margin: 20%;
            }
            
            div {
                border: 1px solid grey;
            }
<header>Header</header>

<main>
<div>Div</div>
</main>

Why is the header not attached to the left viewport edge?

5
“but reaches to the end of the viewport on the right side” - no, it actually goes beyond that, it doesn’t “stop” at the right viewport edge. (Easy to see if you f.e. hover over the element in dev tools.)CBroe

5 Answers

5
votes

Why is the header not attached to the left viewport edge?

Because you did not specify where you want its left edge to be.

You basically left left at the default auto, so it takes the natural position this element would have in the flow if it wasn’t positioned, into account.

Add left: 0, and it will behave like you want it to.

0
votes

Just add left: 0

* {
  box-sizing: border-box;
}

header {
  position: fixed;
  background-color: #59b1ff;
  top: 0;
  left: 0;
  height: 20px;
  width: 100%;
}

body {
  margin: 20%;
}

div {
  border: 1px solid grey;
}
<header>Header</header>

<main>
<div>Div</div>
</main>
0
votes

Actually the problem is with your header element. Whenever you use fixed or absolute positioning, you also have to specify the left, right or top (according to your needs) in your fixed element.

            * {
                box-sizing: border-box;
            }
            
            
        
            header {
                position: fixed;
                background-color: #59b1ff;
                top: 0;
                height: 20px;
                width: 100%;
                left:0;  /*Added this*/
                right:0; /*Added this*/
            }
            
            body {
                margin: 20%;
            }
            
            div {
                border: 1px solid grey;
            }
<header>Header</header>

<main>
<div>Div</div>
</main>
0
votes

Try adding these rules:

header {
  position: fixed;
  background-color: #59b1ff;
  top: 0;
  left: 0; /* stick the header to the viewport's left */
  height: 20px;
  width: 100%;
}

body {
  position: relative; /* allows the header to be positioned relative to the body */
  margin: 20%;
}
0
votes

just set left property zero.you set it default, it will takes the natural position this element would have in the flow.