本文主要介绍如何在网页布局中使用背景图片。先逐个介绍基本的样式,最后介绍样式该如何简写。

1.background-color

设置背景颜色

2.background-image

设置背景图片

3.background-repeat

设置背景图片是否重复

4.background-position

设置背景图片位置,可以设置具体偏移量,也可设置center/left/right/top/bottom,不设默认为center

5.background-size

设置图片大小,第一个为宽,第二个为高,可设置具体值,设置宽度后高度等比例缩放。

可设置cover,图片覆盖整个区域

可设置contain,区域内会完整显示图片

6.background-clip

设置背景的范围。有三个值,border-box,padding-box,content-box.背景颜色会延伸到设置的范围内

7.background-origin

设置背景图片偏移的位置,有三个值,border-box,padding-box,content-box.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .test {
            width: 1000px;
            height: 500px;
            border: 50px dashed #ccc;
            padding: 50px;
            background-color: #f19d9d;
            background-image: url(./img1.jpeg);
            background-repeat: no-repeat;
            /* 第一个为水平偏移量,第二个为垂直偏移量.可设center/left/right,不设默认为center */
            background-position: 200px 50px;
            /* 第一个为宽度,第二个为高度。设一个相当于设了宽度,高度等比例变化 */
            background-size: 200px;
            /* cover:铺满 */
            /* contain:完整显示 */
            /* background-clip控制背景范围 */
            /* border-box:背景色延伸至border,设置虚线可看到 */
            /* background-clip: border-box; */
            /* padding-box:背景色延伸至padding */
            /* background-clip: padding-box; */
            /* content-box延伸至内容区 */
            background-clip: content-box;
            /* background-origin设置偏移圆点 */
            /* border-box设置边框区左上角为原点 */
            /* background-origin: border-box; */
            /* padding-box设置内边距区左上角为原点 */
            /* background-origin: padding-box; */
            /* content-box设置内容区左上角为原点 */
            background-origin: content-box;
        }
    </style>
</head>

<body>
    <div class="test">

    </div>
</body>

</html>

 8.简写形式

语法:

 background: #f19d9d url(./img1.jpeg) no-repeat 200px 50px/200px;

注意:大小要写在位置后

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .test {
            width: 1000px;
            height: 500px;
            border: 50px dashed #ccc;
            padding: 50px;
            background: #f19d9d url(./img1.jpeg) no-repeat 200px 50px/200px;
            background-clip: content-box;
            background-origin: content-box;
        }
        /* 注:大小要写在位置后 */
    </style>
</head>

<body>
    <div class="test">

    </div>
</body>

</html>

 效果如图:

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐