简写属性

date
Mar 6, 2023
slug
deepcss-abbreviated
status
Published
tags
深入解析CSS
summary
CSS Abbreviated attribute
type
Post

简写属性

简写属性是用于同时给多个属性赋值的属性。
  • background 是多个背景属性的简写属性:background-color、background-image、 background-size、background-repeat、background-position、background-origin、 background-chip 以及 background-attachment。
  • border 是 border-width、border-style 以及 border-color 的简写属性,而这几 个属性也都是简写属性。
  • border-width 是上、右、下、左四个边框宽度的简写属性。
font-style、font-weight、font-size、font-height 以 及 font-family
font: italic bold 18px/1.2 "Helvetica", "Arial", sans-serif;

简写属性覆盖其他样式

h1 { 
 font-weight: bold;
} 
.title {
 font: 32px Helvetica, Arial, sans-serif;
}
这样设置 h1 并没有加粗,其等价于
h1 { 
 font-weight: bold;
} 
.title {
 font-style: normal;
 font-variant: normal;
 font-weight: normal;
 font-stretch: normal;
 line-height: normal;
 font-size: 32px;
 font-family: Helvetica, Arial, sans-serif;
}
这些样式也会覆盖从祖先 元素继承的字体样式。

简写值顺序

上、右、下、左

​ 当遇到像 margin、padding 这样的属性,还有为元素的四条边分别指定值的边框属性时,属性的值按顺时针方向,从上边开始。
​ 如果声明结束时四个属性值还剩一个没指定,没有指定的一 边会取其对边的值。指定三个值时,左边和右边都会使用第二个值。指定两个值时,上边和下边会 使用第一个值。如果只指定一个值,那么四个方向都会使用这个值。

水平、垂直

​ 只适用于分别给盒子设置四个方向的值的属性。还有一些属性只支持最多 指定两个值,这些属性包括background-position、box-shadow、text-shadow
​ padding: 1em 2em 先指定了垂直方向的上/下属性值,然后才是水平方向的右/左属性值。
​ background-position: 25% 75%则先指定水平方向的右/左属性值,然后才是垂直方向的 上/下属性值。
​ box-shadow 先指定 x 值再指定 y 值。

© shallrise 2025