Home > Net >  Keep body bg fixed while child elements scroll
Keep body bg fixed while child elements scroll

Time:11-29

So you'll see in my example, I have a gradient applied to html and a texture overlay .png on body which at first looks as expected.

I added a div with a large height to show my issue. Notice as you scroll down in the example you see the div overflow body and the texture overlay applied to body gets cut and almost has a parallax effect.

What I want is the html/body backgrounds to stay fixed so the content of body will scroll over them as expected while the gradient and overlay stay stationary and the size of the window. I'm thinking you'll notice what I'm talking about pretty easily with the example.

What am I missing here?

html, body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

html {
  background: radial-gradient(#bcd197, #325757);
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
}

body {
  outline: blue 3px dashed;
  background-image: url("https://i.ibb.co/NFvCfrj/texture.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
  background-attachment: fixed;
}

div {
  outline: red 3px dashed;
  height: 200rem;
  width: 10rem;
  background-color: rgba(0,0,0,.5);
  margin: 1rem;
}
<div></div>

CodePudding user response:

You're setting the body's height to 100%, so the background no longer render below the initial viewport height.

You must set the same div height to the body or mark body height to auto (default value).

html {
  height: 100%;
  width: 100%;
}

html, body {
  margin: 0;
  padding: 0;
}

body {
  height: auto;
  width: auto;
}

html {
  background: radial-gradient(#bcd197, #325757);
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
}

body {
  outline: blue 3px dashed;
  background-image: url("https://i.ibb.co/NFvCfrj/texture.png");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
  background-attachment: fixed;
}

div {
  outline: red 3px dashed;
  height: 200rem;
  width: 10rem;
  background-color: rgba(0,0,0,.5);
  margin: 1rem;
}
<div></div>

  • Related