【问题标题】:Keep body bg fixed while child elements scroll在子元素滚动时保持 body bg 固定
【发布时间】:2022-11-29 00:50:03
【问题描述】:

所以你会在我的示例中看到,我在html 上应用了渐变,在body 上应用了纹理叠加 .png,乍一看与预期的一样。

我添加了一个高度很大的 div 来显示我的问题。请注意,当您在示例中向下滚动时,您会看到 div 溢出 body 并且应用于 body 的纹理覆盖被剪切并且几乎具有视差效果。

我想要的是 html/body 背景保持固定,这样 body 的内容将按预期滚动它们,同时渐变和叠加层保持静止和窗口大小。我想你会很容易地通过这个例子注意到我在说什么。

我在这里错过了什么?

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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您将 body 的高度设置为 100%,因此背景不再呈现在初始视口高度以下。

    您必须为正文设置相同的 div 高度或将正文高度标记为auto(默认值)。

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2016-03-26
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 2011-12-05
      相关资源
      最近更新 更多