Why does the linear-gradient disappear when I make an element position:absolute?

Add some height to the body to see the background:

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: linear-gradient(20deg, #B7B0F6, #B1D5F9);
  min-height: 100vh;
}

header {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
}
<header>
  <h1>Hello!</h1>
</header>

Your body contain no in-flow element so its height is equal to 0 (same thing for the html height) and this will make the background with a size of 0 thus you will see nothing.

You are not obliged to give a height of 100vh. Even a small padding can be enough due to background propagation. The visual won’t be exactly the same but you will hardly notice this in this case.

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: linear-gradient(20deg, #B7B0F6, #B1D5F9);
  padding:5px;
}

header {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
}
<header>
  <h1>Hello!</h1>
</header>

A small padding on the html too is fine:

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: linear-gradient(20deg, #B7B0F6, #B1D5F9);

}
html {
  padding:2px;
}

header {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
}
<header>
  <h1>Hello!</h1>
</header>

A big padding will make things look different!

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: linear-gradient(20deg, #B7B0F6, #B1D5F9);

}
html {
  padding:40px;
}

header {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%);
}
<header>
  <h1>Hello!</h1>
</header>

You can check this answer to better understand how the propagation is done and how it works with gradient.

Leave a Comment