首页 > 解决方案 > 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?

标签: htmlcss

解决方案


不幸的是,这是不可能的,因为这是固定定位在 CSS 中的工作方式。

发生这种情况的原因是 和 的background-attachment: fixed组合background-size: cover。当您指定background-attachment: fixed它时,它本质上会导致background-imageposition: 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,righttopposition 伪元素停留在它原来的位置。背景可以以通常的方式应用于元素。

请注意,我将片段重命名cplcol

.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>


推荐阅读