左列中的图像需要根据相邻列中内容的高度进行响应。
仅在图像上使用 img-fluid
类是行不通的,因为这不会将图像拉伸(stretch)到所需的高度。
background-size: cover;
是我通常需要的,但随后我需要设置一个固定高度,这与响应式相反。
那么,如何使图像(或背景图像)响应并同时使其与相邻列中内容的高度相匹配?
当前代码:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container-fluid">
<div class="row">
<div class="col-6 px-0">
<img class="img-fluid" src="https://via.placeholder.com/3000x2000" alt="">
</div>
<div class="col-6">
Some text...<br>
more<br>
text<br>
and<br>
stuff<br>
for<br>
more<br>
height
</div>
</div>
</div>
最佳答案
您可以使用绝对定位的内部 div 来包含图像。由于该行是 Flexbox,因此这是将左列缩小到右列文本高度的唯一方法。
<div class="container-fluid px-0">
<div class="row">
<!-- img-fluid normal up to 'md' width -->
<div class="col d-md-none">
<img class="img-fluid" src="https://via.placeholder.com/3000x2000" alt="">
</div>
<!-- from 'md' width onwards convert to flex column
+ add an absolute positioned inner div to contain the image -->
<div class="col-md-6 px-0 d-none d-md-flex flex-column justify-content-center o-hidden">
<div class="position-absolute o-hidden">
<img class="mh-100 mw-100 d-block" src="https://via.placeholder.com/3000x2000" alt="">
</div>
</div>
<div class="col-md-6">
Some text...
<br> more
<br> text
<br> and
<br> stuff
<br> for
<br> more
<br> height
</div>
</div>
</div>
.o-hidden {
overflow:hidden;
}
关于bootstrap-4 - 引导列中的响应(背景)图像以匹配相邻列中内容的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226250/