如何使图像充满Bootstrap 4的容器高度和零售纵横比

时间:2018-12-25 18:28:16

标签: css

图像如何填充父容器的高度并保持宽高比? 我之前使用过类似的模式(请参阅下文),但是我相信Bootstrap 4可能会在这里造成干扰。在移动查看端口中查看图像时,图像在垂直方向拉伸。

div#parent { position: relative; }
h1 { color: #FFF }
img#child { 
    position: absolute;
    min-width: 100%;
    min-height: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: -100;
 }
<div id="parent">
    <img id="child" 
    src="https://cdn.pixabay.com/photo/2016/07/08/08/59/background-1503863_1280.png" alt="Background" />
    <h1>Very very very very very very very very very very very long heading 
    to go over image in mobile view. The image should not stretch 
    vertically.</h1>
</div>

1 个答案:

答案 0 :(得分:0)

background-size: contain;添加到CSS

     img#child {
        position: absolute;
        min-width: 100%;
        min-height: 100%;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: -100;
        background-size: contain;
     }

输出:

enter image description here

有关更多信息:https://www.w3schools.com/csSref/css3_pr_background-size.asp