減少代碼體積、提升可讀性、強制相關屬性聚合聲明、降低維護認知負擔。掌握縮寫順序與默認值陷阱是 CSS 進階必修課。
#000000 → #000
#336699 → #369
#ff0000 → #f00
/* 8位含 Alpha:#rrggbbaa → #rgba */
#ff0000ff → #f00f /* 現代瀏覽器支持 */
/* margin / padding / border-width / border-radius 等 */
property: value1; /* 四邊同值 */
property: value1 value2; /* 上下 | 左右 */
property: value1 value2 value3; /* 上 | 左右 | 下 */
property: value1 value2 value3 value4; /* 上 | 右 | 下 |左 (順時針) */
/* 實例 */
margin: 1em 0 2em 0.5em; /* 上1em 右0 下2em 左0.5em */
padding: 10px 20px; /* 上下10px 左右20px */
border-radius: 8px 4px; /* 左上/右下8px 右上/左下4px */
/* 長手寫 */
border-width: 1px;
border-style: solid;
border-color: #000;
/* 縮寫:順序不強制但慣用 width style color */
border: 1px solid #000;
/* 單邊縮寫 */
border-top: 2px dashed red;
border-right: 1px solid transparent;
/* 長手寫 */
background-color: #f00;
background-image: url(bg.png);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center top;
/* 縮寫:順序 color image repeat attachment position */
/* 現代擴展:size、origin、clip */
background: #f00 url(bg.png) no-repeat fixed center top;
/* 多背景:逗號分隔,第一層最上 */
background:
url(overlay.png) no-repeat center,
url(pattern.png) repeat left top,
linear-gradient(45deg, transparent, rgba(0,0,0,.5));
默認值陷阱:省略值將重置為默認(transparent/none/repeat/scroll/0% 0%),可能覆蓋先前聲明。**建議:單聲明用長手寫,組合聲明用縮寫**。
/* 長手寫 */
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1rem;
line-height: 1.5;
font-family: "Inter", sans-serif;
/* 縮寫:順序嚴格 style variant weight size/line-height family */
/* ⚠️ size/line-height 必須相鄰,family 必須最後 */
font: italic small-caps bold 1rem/1.5 "Inter", sans-serif;
/* 最小合法縮寫 */
font: 1rem/1.5 "Inter", sans-serif; /* 必須有 size 和 family */
/* 長手寫 */
list-style-type: square;
list-style-position: inside;
list-style-image: url(bullet.png);
/* 縮寫:順序 type position image */
list-style: square inside url(bullet.png);
/* 重置最常用 */
list-style: none; /* 同時清除 type、position、image */
background: red; 會重置 background-image 為 none。單屬性修改用長手寫。font: 1rem/1.5 sans-serif 中 1.5 為無單位倍數,推薦。1rem/24px 也合法但不推薦。border-radius: 50% / 25% 水平/垂直半徑分離(橢圓角)。margin-block: 1em; margin-inline: 2em; 適配書寫模式,現代首選。shorthand-property-no-redundant-values 檢測冗餘值。CSS 縮寫是「壓縮算法」而非「簡寫語法」。精通六大體系順序、默認值陷阱、現代擴展語法,配合「單屬性長手、組合縮寫」工程原則,能寫出體積最小、可讀性最高、Bug 最少的樣式代碼。