[CSS]背景图片中平铺与拉伸

在某业务场景下,需要支持背景图的平铺和拉伸,那么在CSS中的这俩属性表现有何区分关系到是否符合业务表现,因此有必要清晰知道其差别。

原本以为只有自己会遇到,没想到群里有小伙伴也问到了。

0x00 background-size

在CSS中有background-size属性,平铺与拉伸可以通过下面两个值实现:

  • 平铺:cover
  • 拉伸:100% 100%

0x01 表现如何

设置的背景图原图比例表现如下:

原图效果

比较的代码实现如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>背景图长宽比例问题探索</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
            border: 0;
        }
        .box {
            width: 400px;
            height: 300px;
            background-color: aquamarine;
            background-image: url(http://p0.qhimg.com/bdr/__85/t01cf4d52137a580601.jpg);
            background-size: cover;
            background-position: center;
        }
        .box2 {
            width: 400px;
            height: 300px;
            background-color: red;
            background-image: url(http://p0.qhimg.com/bdr/__85/t01cf4d52137a580601.jpg);
            background-size: 100% 100%;
            background-position: center;
        }
    </style>
</head>
<body>

    <div class="box"></div>
    <div style="height: 50px;"></div>
    <div class="box2"></div>

</body>
</html>

其浏览器中表现如下图:

表现

可以发现,拉伸是根据容器的宽高来设置图片的宽高,能完整展示整个图片内容,但图像内容发生了变形

而平铺比较特殊,完全展示了图片的高度,但是左右两边被裁掉了一部分,无法展示完整的图片,但图片的宽高比例没变,因此图像不存在变形

将宽高值互换:

.box {
    width: 300px;
    height: 400px;
    background-color: aquamarine;
    background-image: url(http://p0.qhimg.com/bdr/__85/t01cf4d52137a580601.jpg);
    background-size: cover;
    background-position: center;
}
.box2 {
    width: 300px;
    height: 400px;
    background-color: red;
    background-image: url(http://p0.qhimg.com/bdr/__85/t01cf4d52137a580601.jpg);
    background-size: 100% 100%;
    background-position: center;
}

其表现如下:

宽高互换表现

0x02 总结

相较于平铺属性,拉伸的效果非常好理解。平铺,按照我个人理解,平铺的渲染规则是,以图片的“短边”为基准,对图片进行等比例缩放,缩放后的图片“短边”长度等于“短边”所对应容器“边”的长度,“长边”缩放后多余的部分被裁剪。

换句话说,谁短谁牛逼!

参考

发表评论 / Comment

用心评论~

金玉良言 / Appraise
今日新闻LV 1
2021-03-07 23:54
文章不错非常喜欢,支持一下吧
LV 1
2021-01-02 13:33
感谢分享
头像
余归LV 1
2021-09-04 12:21
@菊:哈哈哈哈
站元素主机LV 1
2020-11-28 16:24
学习了 赞一个
今日新鲜事LV 1
2020-11-21 00:54
文章不错非常喜欢

Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23