CSS 縮寫屬性能將多行相關樣式合併為單一宣告,不僅減少檔案體積、加快載入速度,也讓程式碼更易閱讀與維護。掌握核心縮寫規則是前端開發的基本功。
順序:font-style → font-variant → font-weight → font-size/line-height → font-family
/* 完整寫法 */
font: italic small-caps bold 1.2em/1.4em "Microsoft JhengHei", sans-serif;
/* 最小必要:font-size + font-family */
font: 1rem/1.5 "PingFang TC", sans-serif;
⚠️ 注意:font-size 與 line-height 必須以斜線 / 連接,不可分開。
順序:background-color → background-image → background-repeat → background-attachment → background-position
background: #f5f5f5 url("bg.png") no-repeat fixed center top;
順時針方向:上 → 右 → 下 → 左
/* 四值:上 右 下 左 */
margin: 10px 20px 15px 5px;
/* 三值:上 右左 下 */
padding: 1em 2em 1.5em;
/* 兩值:上下 左右 */
margin: 0 auto;
/* 單值:四邊相同 */
padding: 1rem;
順序:border-width → border-style → border-color
border: 2px solid #333;
/* 單邊縮寫 */
border-bottom: 1px dashed #ccc;
順序:list-style-type → list-style-position → list-style-image
list-style: square inside url("bullet.png");
十六進位色碼若每兩碼相同,可縮寫為三碼:
#ffffff → #fff#336699 → #369#f2f2f2 ❌ 無法縮寫(每兩碼不相同)/* 縮寫前:9 行 */
li {
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2em;
line-height: 1.4em;
padding-top: 5px;
padding-bottom: 10px;
padding-left: 5px;
}
/* 縮寫後:4 行 */
li {
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
padding: 5px 0 10px 5px;
}
background: url(img.jpg) 會將 color 重置為 transparent、repeat 重置為 repeatfont 縮寫若省略 font-family 會導致字體回退到瀏覽器預設掌握縮寫後,建議學習 CSS 命名規範與 BEM 方法論,從選擇器層面提升專案可維護性。