适合父div中背景封面的图像宽度

时间:2018-08-18 17:13:42

标签: html css css3

使用引导程序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;
}

它涵盖整个documnet。在 col-9 中,我只能看到一部分图像(对于大图像)

我可以用 col-9 列适合图像的宽度吗?

2 个答案:

答案 0 :(得分:1)

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

发生这种情况的原因是由于background-attachment: fixedbackground-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;将元素固定到相对于视口的设置位置。通过不设置bottomleftrighttop的位置,伪元素将停留在其原始位置。可以按通常的方式将背景应用于元素。

请注意,我将代码段的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>

答案 1 :(得分:0)

要使图像适合其父对象,如果您将图像放在a = np.random.rand(1, 95000)[0] #Python a = rand(1, 95000) #Matlab Python 3.6, Numba 0.40dev, Matlab 2016b, Core i5-3210M Python: 487s Python+Numba: 12.2s Matlab: 71.1s 标签中,则可以执行以下操作:

<img>

查看此stackoverflow post

相关问题