萬盛學電腦網

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

CSS 代碼縮寫技巧大全:margin/padding/border/font/background/color 六大類屬性縮寫規則

CSS 縮寫屬性分類總覽

類別縮寫屬性包含子屬性順序規則
盒模型margin, paddingtop/right/bottom/left順時針(TRBL),1-4 值語法
邊框borderwidth, style, color任意順序,建議 width style color
字體fontstyle, variant, weight, size/line-height, family固定順序,size/family 必填
背景backgroundcolor, image, repeat, attachment, position, size, clip, origincolor image repeat attachment position/size clip origin
列表list-styletype, position, imagetype position image
輪廓outlinewidth, style, color同 border
顏色十六進制#RRGGBB → #RGB雙位重複可縮寫

六大類縮寫詳細規則與示例

1. Margin / Padding(1-4 值語法)

/* 1 值:四方同值 */
margin: 10px;        /* = 10px 10px 10px 10px */

/* 2 值:上下、左右 */
margin: 10px 20px;   /* = 10px 20px 10px 20px */

/* 3 值:上、左右、下 */
margin: 10px 20px 30px;  /* = 10px 20px 30px 20px */

/* 4 值:上、右、下、左(順時針) */
margin: 10px 20px 30px 40px;  /* top right bottom left */

2. Border(三屬性任意順序)

/* 分屬性 */
border-width: 1px;
border-style: solid;
border-color: #333;

/* 縮寫:推薦順序 width style color */
border: 1px solid #333;

/* 單邊縮寫 */
border-top: 2px dashed red;
border-radius: 8px;  /* 圓角不屬於 border 縮寫 */

3. Font(嚴格順序,size/family 必填)

/* 完整 */
font: italic small-caps bold 1rem/1.5 "Microsoft YaHei", sans-serif;
/* 解析:style variant weight size/line-height family */

/* 最小有效 */
font: 1rem "Microsoft YaHei", sans-serif;  /* 必填 size + family */

/* ❌ 無效:缺 family */
font: bold 1rem;

4. Background(現代擴展語法)

/* 經典 */
background: #f00 url(bg.png) no-repeat fixed center;

/* 現代:包含 size、clip、origin */
background: #f00 url(bg.png) no-repeat fixed center / cover content-box padding-box;
/* 解析:color image repeat attachment position / size clip origin */

/* 多背景(逗號分隔,第一層最上) */
background: 
    url(overlay.png) no-repeat center,
    linear-gradient(45deg, #fff, #f0f0f0);

5. List-style

list-style: square inside url(bullet.png);
/* type position image */

6. 十六進制顏色縮寫

#000000 → #000
#336699 → #369
#ff0000 → #f00
#aabbcc → #abc

/* ❌ 無法縮寫:#33669a(非雙位重複) */

實戰對比:縮寫前後

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

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

避坑指南

  • font 縮寫重置未聲明屬性:font: bold 1rem/1.5 sans-serif 會重置 font-variant、font-style 為初始值
  • background 縮寫重置所有背景屬性:後寫的 background-color 會被後來的 background 覆蓋
  • 繼承陷阱:font 縮寫會重置 line-height,子元素繼承計算值而非倍數
  • 邊框圓角:border-radius 不在 border 縮寫中

相關延伸閱讀

CSS 非全局 Reset 方案:Normalize.css 與現代重置最佳實踐

copyright © 萬盛學電腦網 all rights reserved