Skip to content

盒子背景

属性名作用示例
background-color背景颜色background-color: lightblue;
background-image背景图片background-image: url(bg.png);
background-repeat背景平铺方式no-repeat / repeat-x / repeat-y
background-position背景图片位置center center / 10px 20px
background-size背景图片大小cover / contain / 100px 50px
background-attachment背景图滚动方式scroll / fixed / local
background复合写法background: #fff url(bg.png) no-repeat center / cover;

background-color

css
background-color: #f0f0f0;

background-image

css
background-image: url("images/bg.png");

background-repeat

css
background-repeat: repeat;     /* 默认:平铺 */
background-repeat: no-repeat;  /* 不平铺 */
background-repeat: repeat-x;   /* 仅横向平铺 */
background-repeat: repeat-y;   /* 仅纵向平铺 */

background-position

background-position 用于指定背景图片相对于 背景定位区域(background-origin) 的位置。

常见取值:

类型示例含义
关键字left top / center center / right bottom使用方位词来定位
长度值10px 20px从左边10px,从上边20px
百分比50% 0%相对于容器宽高的百分比定位
单值写法center相当于 center center
css
background-position: <x-position> <y-position>;

默认值:背景图片的左上角对齐到背景区域的左上角

css
background-position: left top;

background-size

background-size 用来设置背景图片在元素中的尺寸。

css
background-size: <width> <height>;

常见取值:

取值说明示例
auto保持原始大小(默认)background-size: auto;
<length>使用具体长度(px / em / rem)background-size: 100px 50px;
<percentage>相对于容器尺寸的百分比background-size: 50% 100%;
cover按比例放大,铺满容器,可能裁剪图片常用于全屏背景
contain按比例缩放,完整显示图片,可能留空白常用于展示完整图

background-attachment

background-attachment 是控制 背景图是否随页面滚动 的属性, 经常用于实现「固定背景(视差滚动)」效果。

说明背景滚动行为
scroll(默认)背景随元素内容滚动,但不随页面滚动默认表现
fixed背景**固定在视口(屏幕)**上,不随页面滚动常用于全屏固定背景
local背景随元素内容一起滚动通常配合 overflow: auto 使用

当你设置 background-attachment: fixed 时:

  • 背景图位置(background-position)不再相对于元素,而是参考 浏览器视口(viewport)。

  • 无论页面或元素滚动,背景图都保持在同一位置。

  • 背景图还是属于这个元素,只是位置参考改成了视口,用户可以通过这个元素看到background-image的效果

background

css
background: <bg-color> <bg-image> <bg-repeat> <bg-attachment> <bg-position> / <bg-size> ;

案例:视差滚动效果

点击跳转链接