img图片实现缩放平铺填充

背景: 图片展示不仅仅可以设置宽高, 还有对应的css属性

object-fit 属性

指定元素的内容应该如何去适应指定容器的高度与宽度。

object-fit 一般用于 img 和 video 标签,一般可以对这些元素进行保留原始比例的剪切、缩放或者直接进行拉伸等。

html代码:

    <div style='height:300px;300px; background-color: pink; display: block;'>
        <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="border: 1px solid red;">
    </div>

    <p>原图片标签</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="">

    <p>object-fit: fill; 拉伸/缩小填充</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: fill;">

    <p>object-fit: contain; 保持宽高缩放填充</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: contain;">

    <p>object-fit: cover; 保持宽高比填充,超出部分裁剪</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: cover;">

    <p>object-fit: none; 保持宽高比填充,超出部分裁剪</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: none;">

    <p>object-fit: scale-down; 内容的尺寸与 none 或 contain 中的一个相同,取决于它们两个之间谁得到的对象尺寸会更小一些</p>
    <img src="https://www.baidu.com/img/flexible/logo/pc/result.png" alt="" style="object-fit: scale-down;">

css代码:

        div {
            margin: 10px;
            display: inline-block;
        }

        img {
            height: 300px;
             300px;
            border: 1px solid red;
        }
原文地址:https://www.cnblogs.com/xihailong/p/14000775.html