萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 代碼縮寫技巧大全:margin、padding、border、font、background、色彩值

核心縮寫屬性對照表

屬性類別展開寫法縮寫寫法值順序規則
Margin / Paddingmargin-top: 5px; margin-right: 10px; margin-bottom: 15px; margin-left: 20px;margin: 5px 10px 15px 20px;1值:四邊同值
2值:上下、左右
3值:上、左右、下
4值:上、右、下、左 (順時針)
Borderborder-width: 1px; border-style: solid; border-color: #ccc;border: 1px solid #ccc;寬度 樣式 顏色(順序不嚴格,建議固定)
Border 单边border-top-width: 1px; border-top-style: solid; border-top-color: #ccc;border-top: 1px solid #ccc;同上
Fontfont-style: italic; font-variant: small-caps; font-weight: bold; font-size: 1em; line-height: 1.5; font-family: Arial, sans-serif;font: italic small-caps bold 1em/1.5 Arial, sans-serif;style variant weight size/line-height family(size/family 必填)
Backgroundbackground-color: #fff; background-image: url(/bg.png); background-repeat: no-repeat; background-position: center top; background-attachment: fixed;background: #fff url(/bg.png) no-repeat center top fixed;color image repeat position attachment(順序不嚴格)
Color (HEX)#FF0000, #00FF00, #0000FF#F00, #0F0, #00F三位數縮寫:各通道雙數字相同時(如 FF→F, 00→0)

實戰前後對比

/ * 縮寫前 * /
li {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 1.2em;
    line-height: 1.4em;
    padding-top: 5px;
    padding-bottom: 10px;
    padding-left: 5px;
}

/ * 縮寫後 * /
li {
    font: 1.2em/1.4em Arial, Helvetica, sans-serif;
    padding: 5px 0 10px 5px;  /* 上 右 下左 */
}

進階縮寫技巧

1. margin/padding 兩值/三值實用場景

/ * 垂直間距相同、水平間距相同 * /
margin: 1rem 2rem;      /* 上下 1rem, 左右 2rem */

/ * 上下不同、左右相同 * /
padding: 1rem 2rem 1.5rem; /* 上 1rem, 左右 2rem, 下 1.5rem */

2. border-radius 縮寫

/ * 四角不同 * /
border-radius: 4px 8px 12px 16px; /* 左上、右上、右下、左下 */

/ * 八值語法(水平/垂直半徑分離) * /
border-radius: 4px 8px 12px 16px / 2px 4px 6px 8px;

3. background-size / background-origin / background-clip (CSS3)

background: url(/img.jpg) no-repeat center / cover content-box border-box;
/* image repeat position / size origin clip */

色彩值縮寫最佳實踐

  • 六位數 #RRGGBB 為標準,三位數 #RGB 僅在三通道皆為雙重複數字時使用(#F00、#0F0、#00F、#FFF、#000、#888 等)。
  • 避免混用大小寫,統一大寫(#FF33AA)利於 Gzip 壓縮與程式碼閱讀。
  • 需透明度請用 rgba() / hsla() / #RRGGBBAA (8 位 HEX, CSS Color Level 4)。

小結

熟練掌握 CSS 縮寫屬性,能大幅減少代碼行數、提升閱讀效率、縮小檔案體積。關鍵在於記住值順序規則(順時針)與必填項(font-size/font-family),並建立團隊統一的程式碼風格指南。

copyright © 萬盛學電腦網 all rights reserved