首页 > 解决方案 > 使 div 高度适合背景图像高度(具有视差效果)

问题描述

我检测到 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>

标签: htmlcssbackground-imageparallax

解决方案


使用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>


推荐阅读