使用引导程序4:我有以下代码:
我想在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>我使用这个css代码:
.parallax {
min-height: 300px;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}它覆盖了整个纪录片。在col-9中,我只能看到图像的一部分(对于大型图像)。
我能用-9列来拟合图像的宽度吗?
发布于 2018-08-18 18:42:23
不幸的是,这是不可能的,因为这是固定定位工作在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;将元素固定到相对于视图端口的设置位置。通过不设置bottom、left、right或top位置,伪元素将保持原来的位置。背景可以按通常的方式应用于元素。
注意,我将代码段的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>
发布于 2018-08-18 17:44:24
https://stackoverflow.com/questions/51910970
复制相似问题