Shorthand properties 表示 CSS 中有一些属性,它包含了多个其他属性的信息,比如:
background-color: #000;
background-image: url(images/bg.gif);
background-repeat: no-repeat;
background-position: left top;可以简写成:
background: #000 url(images/bg.gif) no-repeat left top;Edge Cases
background-color: red;
background: url(images/bg.gif) no-repeat left top;Shorthand properties 允许它其中有部分信息缺失,比如上面的 background 中没有写上颜色。但是这会导致缺失的属性被设成初始值,比如上面的例子中,背景颜色会是初始的 transparent 而不是 red。
inherit 关键字用在 shorthand property 上面时,是整体的继承,而不是对里面的单个元素做继承。
1-to-4-value Syntax
对于 padding, margin, border-width 等有上下左右 4 个方向值的,它的 shorthand property 可以不写全 4 个值,1-3 个值都是可以的。不同情况上对应的数值如下:
| Value Example | top | right | bottom | left |
|---|---|---|---|---|
border-width: 1em | 1em | 1em | 1em | 1em |
border-width: 1em 2em | 1em | 2em | 1em | 2em |
border-width: 1em 2em 3em | 1em | 2em | 3em | 2em |
border-width: 1em 2em 3em 4em | 1em | 2em | 3em | 4em |
对于 border-radius 这类看角而不是看边的,顺序变成了 top-left, top-right, bottom-right, bottom-left。
对于仅有两个方向的属性,比如 background-position: 25% 75%,它的顺序是先水平后垂直。