使div高度适合背景图像的高度(具有视差效果)

时间:2019-03-02 19:10:11

标签: html css background-image parallax

我检测到100%宽度的视差背景图像有问题。我必须使用div height的固定值,因为它是空的。

问题是:视口狭窄时,背景图像下的空白区域。 问:如何创建与背景图像高度相等的自适应div高度。

我当前的搜索和尝试:

// tried, but didn't work

// <div class="parallax">
//   <img src="https://images.pexels.com/photos/574205/pexels-photo-574205.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260">
// </div>

// img{
//   visibility: hidden;
//   max-width: 100%;
// }

//second method didn;t work too
// .parallax{
//   background-image: url("https://images.pexels.com/photos/574205/pexels-photo-574205.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
//   background-attachment: fixed;
//   background-repeat: no-repeat;
//   background-size: 100% auto;
//   padding-top: 60%;
//   height: 0;
// }
html, body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.empty-space-20{
  height: 20vh;
  background-color: lime;
}



.parallax{
  background-image: url("https://images.pexels.com/photos/574205/pexels-photo-574205.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 100% auto;
  height: 40vh;
}



.empty-space{
  height: 1000px;
  background-color: coral;
}
<div class="empty-space-20">some empty space</div>
<div class="parallax"></div>

<div class="empty-space">some empty space</div>

1 个答案:

答案 0 :(得分:0)

使用vw而非vh可以提高响应速度,并避免图像下方留有空间。图像的高度在不断变化,以保持其比例,因此对div也是一样。您还可以将图像的位置调整为在该div内部分层。

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

.empty-space-20{
  height: 20vh;
  background-color: lime;
}



.parallax{
  background-image: url("https://images.pexels.com/photos/574205/pexels-photo-574205.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: 0 20vh;
  height: 50vw;
}



.empty-space{
  height: 1000px;
  background-color: coral;
}
<div class="empty-space-20">some empty space</div>
<div class="parallax"></div>

<div class="empty-space">some empty space</div>

如果您不希望任何滚动空间,请降低高度,如下所示,并保留背景的默认位置:

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

.empty-space-20{
  height: 20vh;
  background-color: lime;
}



.parallax{
  background-image: url("https://images.pexels.com/photos/574205/pexels-photo-574205.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: 100% auto;
  height: calc(50vw - 20vh);
}



.empty-space{
  height: 1000px;
  background-color: coral;
}
<div class="empty-space-20">some empty space</div>
<div class="parallax"></div>

<div class="empty-space">some empty space</div>