代码之家  ›  专栏  ›  技术社区  ›  Hammerbot

固定背景图像和绝对定位包装

  •  1
  • Hammerbot  · 技术社区  · 8 年前

    我只对谷歌浏览器有意见。基本的css样式在两个浏览器上的行为不一样,我不明白为什么。

    下面是firefox上的行为,这是期望的结果:

    enter image description here

    下面是Chrome的行为,这是不好的,因为图像在scroll上向下滚动:

    enter image description here

    您可以在这个jsfiddle上复制它: https://jsfiddle.net/zcugdayv/26/

    为了解决这个问题,我试图将代码减少到最小:

    .app {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
    }
    
    .parallax-wrapper {
      height: 100vh;
      background: url('http://m0.libe.com/blogs/cache/3e/9f/3e9f3c94db337827f6d1d0a859a433f4.jpg') fixed center;
      background-size: cover;
    }
    
    .normal-wrapper {
      height: 600px;
      background: green;
    }
    <div class="app">
      <div class="parallax-wrapper"></div>
      <div class="normal-wrapper"></div>
    </div>

    我知道如果我不使用 position: absolute; 上 app 类它再次工作,但我需要这个不同的原因。

    你认为这是google chrome本身的一个bug,并且在将来的版本中会被修复,或者是google chrome本身出于某种特殊原因而实现的新功能吗?

    如果google chrome上的行为正常,为什么图像会下降?我看到的数学是什么?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Armin Ayari    8 年前

    更新的代码段:

    看看这段代码我想这可以解决你的问题:

    * {
      margin: 0;
      padding: 0;
    }
    
    body {
      position: relative;
      width: 100%;
    }
    
    #app {
      position: absolute;
      width: inherit;
    }
    
    div div {
      width: 100%;
      height: 100vh;
      background: red;
    }
    
    div.parallax-wrapper {
      background-image: url('http://m0.libe.com/blogs/cache/3e/9f/3e9f3c94db337827f6d1d0a859a433f4.jpg');
      background-repeat: no-repeat;
      background-size: cover;
      background-position: center;
      background-attachment: fixed;
    }
    <body>
      <div id="app">
        <div class='parallax-wrapper'></div>
        <div class="normal-wrapper">Hello World</div>
        <div class='parallax-wrapper'></div>
        <div class="normal-wrapper">Hello World</div>
      </div>
    </body>

    你也可以在这里看到结果: https://jsbin.com/mebecirino/edit?html,css,output

        2
  •  1
  •   Sam Pearson    8 年前

    我不确定为什么在chrome中会发生这种情况,但我已经为您做了一个变通方法。在每个规则中添加以下内容,应该可以正常工作。

    .parallax-wrapper {
        position: fixed;
        top: 0;
        width: 100%;
    }
    .normal-wrapper {
        margin-top: 100vh;
        z-index: 1;
        position: relative;
    

    }