视差背景不包括溢出的内容

时间:2018-05-21 00:23:05

标签: css parallax

我想根据https://keithclark.co.uk/articles/pure-css-parallax-websites/创建一个视差效果。

使用该解决方案,背景不会涵盖溢出的内容。 我希望在滚动时看到背景图像的下半部分而不是空白区域。

.parallax {
  overflow-x: hidden;
  overflow-y: scroll;
  height: 150px;
  perspective: 1px;
}

.parallax__layer {
    position: absolute;
    color:white;
    padding-left: 20px;
    top: 0;
}

.parallax__layer--back {
    background: url('https://www.w3schools.com/w3images/nature.jpg');
    transform: translateZ(-2px) scale(3);
    background-size: cover;
    background-position: top;
    height: 100%;
    /* height: contentHeight */
}
<div class="parallax">
   <div class="parallax__layer--back"></div>
   <div class="parallax__layer">
      <h1>
         Any content <br/><br/>
         that <br/><br/>
         causes <br/><br/>
         overflow <br/><br/>
      </h1>
   </div>
 </div>

是否有规则可以实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可能已经注意到,这是由于使用了height:100%。另一个想法是使用图层作为主要内容的伪元素,你可以使它适合它的高度:

&#13;
&#13;
.parallax {
  overflow-x: hidden;
  overflow-y: scroll;
  height: 150px;
  perspective: 1px;
}

.parallax__layer {
    position: absolute;
    color:white;
    padding-left: 20px;
    top: 0;
    left:0;
    right:0;
}

.parallax__layer:before {
    content:"";
    position:absolute;
    left:0;
    top:0;
    right:0;
    background: url('https://www.w3schools.com/w3images/nature.jpg');
    transform: translateZ(-2px) scale(3);
    background-size: cover;
    background-position: top;
    height: 100%;
    z-index:-1;
}
&#13;
<div class="parallax">
   <div class="parallax__layer">
      <h1>
         Any content <br><br>
         that <br><br>
         causes <br><br>
         overflow <br><br>
      </h1>
   </div>
 </div>
&#13;
&#13;
&#13;

相关问题