html - fit width of image for background cover in parent div
问题描述
with bootstrap 4: I have this code:
I want add a fixed cover background in col-9
<div class="container">
<div class="row">
<div class="cpl-3">...</div>
<div class="cpl-9">
<div class="parallax" style="background-image: url('pic.jpg');"></div>
</div>
</div>
</div>
I use this css code:
.parallax {
min-height: 300px;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
It cover whole documnet. In col-9, I can only see a part of image (for large images)
can I fit width of image with col-9 column?
解决方案
不幸的是,这是不可能的,因为这是固定定位在 CSS 中的工作方式。
发生这种情况的原因是 和 的background-attachment: fixed
组合background-size: cover
。当您指定background-attachment: fixed
它时,它本质上会导致background-image
它position: fixed
像图像一样表现,这意味着它已脱离页面流和定位上下文,并相对于视口而不是它作为背景图像的元素。
因此,无论何时一起使用这些属性,cover
都会相对于视口的大小计算该值,而与元素本身的大小无关,这就是为什么当元素与视口大小相同但被裁剪时它会按预期工作的原因当元素小于视口时的意外方式。
有一个解决方法,请注意,这不是一个完美/干净的解决方案
position: fixed;
您可以通过使用伪元素来实现类似的预期结果:
- 添加
.parralax:before
具有以下规则 的新选择器background-image: url();
- 背景图片background-repeat: no-repeat;
- 停止背景重复content: "";
- 显示伪元素所必需的position: fixed;
- 将伪元素设置为相对于视口固定height: 100%;
- 使伪元素填满整个高度width: 75%;
- 与宽度相同col-9
position: fixed;
将元素固定到相对于视口的设定位置。通过不设置 a bottom
, left
,right
或top
position 伪元素停留在它原来的位置。背景可以以通常的方式应用于元素。
请注意,我将片段重命名cpl
为col
.parallax {
position:relative;
min-height:300px;
}
.parallax:before {
content: "";
position: fixed;
height: 100%;
background-image: url(https://placehold.it/1000x1000);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
width:75%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-3">...</div>
<div class="col-9">
<div class="parallax" ></div>
</div>
</div>
</div>
推荐阅读
- c++ - 为什么使用 cin.clear() 不清除输入?
- c# - 如何读取存储在 Azure 存储中的 excel 文件作为 Blob 文件
- c# - 如何通过 Unity 中的 2 个场景共享分数
- mysql - MySQL-为什么这个查询使用全索引扫描?
- javascript - 如何通过组合多个正则表达式来形成正则表达式
- java - 应用程序在 Playstore 上发布时 OkHttp 连接超时
- flutter - Flutter - 滚动控制器没有被监听
- docusignapi - 如何在 DocuSign 中按用户管理模板?
- mysql - MySQL 默认空值
- swift - 快速声明变量