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

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

ZJ
ZJ
2020-10-22 / 0 评论 / 241 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2020年10月22日,已超过1281天没有更新,若内容或图片失效,请留言反馈。

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

background-size

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

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


表现如何

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

比较的代码实现如下:

<!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  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;
}

其表现如下:

总结

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

本文共 334 个字数,平均阅读时长 ≈ 1分钟
0

评论 (0)

取消