'HTML margin affecting fixed element on left-hand side only

I have a simple HTML document (snip):

<html lang="en">

<body>
    <div class="background"></div>
    <header class="main-header">
        <div>
            <a href="../index.html" class="main-header__brand">
                uHost
            </a>
        </div>
    </header>
    </div>
</body>
</html>

I noticed the following.

If I apply the following style:

background {
    background: url('../images/macbook.jpeg');
    position: fixed;
    height: 100%;
    z-index: -1;
    width: 100%;
}

Then the background image covers the whole viewport as expected.

If I then add:

html {
    margin-left: 10%;
    margin-right: 10%;
}

The margin is correctly applied to the left and right of my content. But also to the left side only of the background. Ie: enter image description here

I am confused as to why, as I thought fixed elements were positioned relative to the viewport? So why is a style on the html element influencing the rendering of the background?

As a solution to get what I wanted (some margin on both sides), I can do something like:

html {
    width: 80vw;
    margin: auto;
}

.background {
    background: url('../images/macbook.jpeg');
    position: fixed;
    height: 100%;
    z-index: -1;
    width: 80vw;

}

Which produces:

enter image description here

But again, I'm unsure why the margin property on the html element is affecting my fixed background div?



Solution 1:[1]

When using position fixed, the element will still follow its natural initial placement, unless otherwise specified via the top left bottom or right attributes. Here you can see, even though the body element has a margin of 10px, the background element is still at the top left.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 10px;
}

h1 {
 color: white;
 text-align: center;
}

.background {
  background-image:         url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Solar_Eclipse_May_20%2C2012.jpg/1024px-Solar_Eclipse_May_20%2C2012.jpg"); 
  width: 300px;
  height: 300px;
  background-size: cover;
  z-index: -1;
  position: fixed;
  top: 0;
  left: 0;
}
<body>
  <div class="background">
    <h1> Solar Eclipse </h1>
  </div>
</body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alechristopher