html - 使 div 高度适合背景图像高度(具有视差效果)
问题描述
我检测到 100% 宽度视差背景图像存在问题。我必须使用 div 高度的固定值,因为它是空的。
问题是:当视口很紧时,背景图像下的空白空间。问:如何创建一个响应式 div 高度等于背景图像高度。
我目前的搜索和尝试:
尝试了两种最流行的方法都没有效果,
准备codepen:https ://codepen.io/SeboFE/pen/xBVjzQ
// 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>
解决方案
使用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>
推荐阅读
- python - Robot Framework 如何获取文本项
- c# - 从 var 中获取值
- java - 旋转 x 轴标签时,MPAndroidChart 图表在数据集更改时垂直调整大小
- java - 如何根据jpa @query方法中的嵌套实体属性对数据进行排序
- python - 函数 *args 的字典解包列表
- javascript - ES6 Array filter() 方法未按预期工作
- path - 将我自己的 cls 文件放入 Texlive 2020
- android - Flutter Sqflite 地图对象显示 setter 在 null 上被调用
- python - urllib.error.HTTPError:HTTP 错误 413:有效负载太大
- flutter - Flutter ExpansionTile 标题垂直填充