文章目录


background-color 设置背景颜色
background-image 设置背景图片

如果背景图片大小小于元素,则背景图片会自动在元素中平铺将元素铺满
如果背景图片大小大于元素,则背景图片一部分会无法完全显示
如果背景图片大小等于元素,则背景图片会直接正常显示

background-repeat 设置背景图片的重复方式

repeat 默认值,背景图片沿着x轴和y轴双方向重复
repeat-x 背景图片沿着x轴方向重复
repeat-y 背景图片沿着y轴方向重复
no-repeat 背景图片不重复

background-position 设置背景图片的位置

通过top left right bottom center几个表示方位的词来设置背景图片的位置:使用方位词时必须要同时指定两个值,如果只写一个则第二个默认就是center
通过偏移量来指定背景图片的位置:水平方向偏移量、垂直方向变量

background-clip 设置背景的范围

border-box 默认值,背景会出现在边框的下边
padding-box 背景不会出现在边框,只出现在内容区和内边距
content-box 背景只会出现在内容区

background-origin 背景图片的偏移量计算的原点

border-box 背景图片的变量从边框处开始计算
padding-box 默认值,background-position从内边距处开始计算
content-box 背景图片的偏移量从内容区处计算

background-size 设置背景图片的大小

第一个值表示宽度,第二个值表示高度;如果只写一个,则第二个值默认是auto
cover 图片的比例不变,将元素铺满
contain 图片比例不变,将图片在元素中完整显示

background-attachment 背景图片是否跟随元素移动

scroll 默认值,背景图片会跟随元素移动
fixed 背景会固定在页面中,不会随元素移动

.box1 {
    height: 500px;
    width: 500px;
    overflow: auto;
    border: 20px red double;
    padding: 10px;
    /* 背景色 */
    background-color: darksalmon;
    /* 背景图 */
    background-image: url('/assets/背景.png');
    /* 背景图重复方式 */
    background-repeat: no-repeat;
    /* 背景图偏移位置 */
    background-position: 0 0;
    /* 背景图偏移量计算的原点 */
    background-origin: content-box;
    /* 背景范围 */
    background-clip: content-box;
    /* 背景图片大小 */
    background-size: contain;
}

.box2 {
    width: 100px;
    height: 1000px;
    background-color: orange;
    background-image: url("assets/背景2.jpg");
    background-repeat: no-repeat;
    background-position: 50px 50px;
    /* 背景图片是否跟随移动 */
    background-attachment: fixed;
}