将div高度调整为背景图像高度(具有视差效果)

问题描述 投票:0回答:1

我已经检测到100%宽度视差背景图像的问题。我要使用div高度的固定值,因为它是空的。

问题是:当视口很紧时,背景图像下的空白空间。问:如何创建响应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>
html css background-image parallax
1个回答
0
投票

使用vw而不是vh来获得更好的响应并避免图像下的空间。图像在高度上保持不变,保持它的比例,所以你对div做同样的事情。您还可以将图像的位置调整到该div内的strat。

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>
© www.soinside.com 2019 - 2024. All rights reserved.