css background简写属性共可设置8个子属性(不含background-blend-mode),按规范顺序为:background-color、background-image、background-repeat、background-attachment、background-position/background-size、background-origin、background-clip;未指定项取默认值,如transparent、none、repeat、scroll、0% 0%、auto auto、border-box等。

看浏览器开发者工具里 computed 样式里的 background 值
直接打开 DevTools → Elements → 右侧 Styles 面板 → 找到 background 行,点开它展开的 computed 值。这里显示的是最终生效的完整简写值(比如 rgb(240, 240, 240) url("bg.jpg") no-repeat center/cover fixed padding-box border-box),它已经隐含了所有被覆盖的子属性。
注意:computed 值不会告诉你哪些子属性“没被写”,只告诉你当前实际生效的是什么。真正要判断「覆盖了哪些」,得反向拆解这个 computed 值,对照语法顺序和默认值规则来推断。
按语法顺序逐段匹配,识别显式设置项
CSS 规范允许 background 简写中值的顺序是灵活的,但有两条硬约束:
-
background-position和background-size必须成对出现,中间用/隔开(如center/cover);没写/就说明没设size -
background-color如果出现在最末尾且是颜色值(如red、#fff、transparent),基本就是它;如果出现在开头或中间,大概率是background-image的 fallback 色(但仅当 image 加载失败时才生效) - 出现
url(...)或linear-gradient(...)就代表设置了background-image - 出现
no-repeat、repeat-x等就是background-repeat - 出现
fixed就是background-attachment;出现padding-box、content-box等就是background-origin或background-clip
例如:background: #eee url(img.png) top left/50% auto repeat fixed; —— 这里明确覆盖了 background-color、background-image、background-position、background-size、background-repeat、background-attachment,但没提 origin 和 clip,所以它们取默认值 border-box。
没写的子属性会回退到默认值,不是“没生效”
很多人误以为不写某个值就等于“禁用”,其实不然。所有未在简写中出现的子属性,都会使用其 CSS 默认值:
-
background-color默认是transparent -
background-image默认是none -
background-repeat默认是repeat -
background-position默认是0% 0% -
background-size默认是auto auto -
background-attachment默认是scroll -
background-origin和background-clip默认都是border-box
这意味着:哪怕你只写 background: red;,也等价于设置了 background-color: red;,其余 7 个子属性全按默认走——不是“没覆盖”,而是“覆盖成了默认值”。
多背景图场景下 color 只能出现在最后一层末尾
当用逗号分隔多个背景层时(如 background: url(a.jpg), url(b.png) bottom, #333;),background-color 必须且只能出现在最后一个逗号之后、整条声明的末尾位置。如果它出现在中间或开头,会被当作某一层的 background-image fallback 色,而不是最终背景色。
这种写法容易出错,尤其复制粘贴时漏掉末尾逗号或错位。建议在多背景图中显式分离 background-color:
element {
background: url(a.jpg), url(b.png) bottom;
background-color: #333;
}
这样逻辑更清晰,也避免因顺序误解导致颜色不生效。
真正难判断的其实是 background-origin 和 background-clip 的双值写法:单个值(如 padding-box)同时作用于二者;两个值(如 content-box border-box)前者是 origin,后者是 clip。这个细节在 DevTools 的 computed 面板里不会标注来源,必须靠手动拆解确认。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











