强制div高度以适合透视的内容

时间:2018-03-22 15:25:10

标签: html css

我正在尝试使用提供的here技术,使网站的背景滚动速度低于内容。我不希望修复背景,只是更慢。

这是HTML的样子:

.parallax {
  perspective: 1px;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
}

.parallax_group {
  position: relative;
  width: 960px;
  transform-style: preserve-3d;
  height: 100%; /* <--- PROBLEM HERE */
}

.parallax_layer {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.background {
  background-image: url("https://static.pexels.com/photos/531880/pexels-photo-531880.jpeg");
  background-position: top;
  background-size: 960px 1000px;
  background-repeat: repeat-y;
  transform: translateZ(-1px) scale(2);
}

.page {
  transform: translateZ(0) scale(1);
}
<div class="parallax">
  <div class="parallax_group">
    <div class="background parallax_layer"></div>
    <div class="page parallax_layer">
      <p>Line 1</p>
      <p>Line 2</p>
      <p>Line 3</p>
      <p>Line 4</p>
      <p>Line 5</p>
      <p>Line 6</p>
      <p>Line 7</p>
      <p>Line 8</p>
      <p>Line 9</p>
      <p>Line 10</p>
    </div>
  </div>
</div>

它可以创建视差效果。但问题是包含背景的div具有固定大小,这里100%被解释为视差div的大小,而不是内容的大小。但内容因页面而异。如果我给背景一个固定的大小,那么在某些页面上它会太长而在其他页面上太短。

例如,如果内容有很多行,它将溢出背景。如果内容只有几行,则背景将无用长。

我尝试了各种技巧使其扩展到内容(例如flex),但没有任何效果,背景总是有固定的大小。我唯一没有尝试过的是javascript。在CSS中没有办法做到这一点吗?

更新:我修改了HTML以更好地显示问题。如果您运行代码段并完全向下滚动,您将看到第9行和第10行后面没有背景,因为显示背景的div不够高。

1 个答案:

答案 0 :(得分:0)

尝试删除.background类中固定的background-size。

我已经创建了一个片段来测试它,看起来它也可以用于不同的图像,但是如果你可以提供你想要设置为背景的图像的某些尺寸,我可以做进一步的测试。

.parallax {
  perspective: 1px;
  height: 400px;
  overflow-x: hidden;
  overflow-y: auto;
}

.parallax_group {
  position: relative;
  width: 960px;
  transform-style: preserve-3d;

  height: 100%;  /* <--- PROBLEM HERE */

}

.parallax_layer {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.background {
  background-image: url("https://static.pexels.com/photos/531880/pexels-photo-531880.jpeg");
  background-position: top;
  background-repeat: repeat-y;
  transform: translateZ(-1px) scale(2);
}

.page {
  transform: translateZ(0) scale(1);
}
<div class="parallax">
  <div class="parallax_group">
    <div class="background parallax_layer"></div>
    <div class="page parallax_layer">
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
      <p>Content...</p>
    </div>
  </div>
</div>

相关问题