盒子背景
| 属性名 | 作用 | 示例 |
|---|---|---|
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> ;案例:视差滚动效果
点击跳转链接
