萬盛學電腦網

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

CSS 簡寫屬性完全指南:Margin、Padding、Border、Background、Font

為什麼要用簡寫?

  • 減少代碼體積(傳輸更快)。
  • 集中管理相關屬性,降低維護成本。
  • 瀏覽器解析較快(少數屬性合併計算)。

盒模型簡寫

Margin / Padding

/* 四值:上 右 下 左(順時針) */
margin: 10px 20px 30px 40px;

/* 三值:上 左右 下 */
margin: 10px 20px 30px;

/* 二值:上下 左右 */
margin: 10px 20px;

/* 一值:四邊相同 */
margin: 10px;

/* 邏輯屬性(現代,支援 RTL) */
margin-block: 10px 20px;   /* 上 下 */
margin-inline: 10px 20px;  /* 左 右 */

Border

/* 完整:寬度 樣式 顏色 */
border: 1px solid #ccc;

/* 單邊 */
border-top: 2px dashed red;
border-right: 1px solid;
border-bottom: 3px double #000;
border-left: 1px solid;

/* 邏輯屬性 */
border-block: 1px solid;
border-inline: 2px dashed red;

Border-radius

/* 四角同值 */
border-radius: 8px;

/* 四值:左上 右上 右下 左下 */
border-radius: 8px 16px 24px 32px;

/* 八值:水平半徑 / 垂直半徑(橢圓角) */
border-radius: 50% 20% / 30% 40%;

Background 簡寫

/* 完整順序:color image repeat attachment position / size origin clip */
background: #fff url(bg.png) no-repeat fixed center / cover content-box border-box;

/* 常用精簡 */
background: #f5f5f5 url(bg.jpg) no-repeat center / cover;
background: linear-gradient(45deg, #f00, #0f0) no-repeat;

注意:background-size 必須在 position 後用 / 分隔;origin/clip 同值時只寫一次,不同值則第一個為 origin、第二個為 clip。

Font 簡寫

/* 必須順序:style variant weight stretch size/line-height family */
font: italic small-caps bold 1.2rem/1.5 "PingFang TC", sans-serif;

/* 最小必要:size/line-height family */
font: 1rem/1.5 system-ui, sans-serif;
  • line-height 必須緊跟 font-size 並用 / 分隔。
  • 省略項目會重置為初始值(如 font-weight: normal),小心覆蓋繼承值。

其他常用簡寫

屬性簡寫範例展開
list-stylelist-style: square inside url(bullet.png);type position image
outlineoutline: 2px solid red;width style color
flexflex: 1 1 300px;grow shrink basis
gridgrid: auto-flow dense / 1fr 2fr;template-rows / template-columns
animationanimation: fade 1s ease-in 0s 2 normal forwards;name duration timing delay count direction fill-mode
transitiontransition: all 0.3s ease;property duration timing delay

顏色值簡寫

/* HEX 3 位數 */
#abc  →  #aabbcc
#rgba → #rrggbbaa  (8 位數)

/* RGB 現代語法 */
rgb(255 0 0 / 50%)
hsl(120 50% 50% / 0.8)

避坑指南

  • 簡寫會重置未指定的子屬性:background: red; 會把 background-image 重置為 none。
  • 順序錯誤導致無效:font: 1rem "Serif" bold; 錯誤(weight 必須在 size 前)。
  • 邏輯屬性與物理屬性混用:同一規則集盡量統一風格。
  • CSS-in-JS/原子化 CSS:Tailwind 等工具已將簡寫內建,手寫時仍需理解展開形式以便除錯。

總結

CSS 簡寫是「寫少做多」的藝術。熟記 順時針四值、font 必須順序、background 斜線分隔 size 三大核心規則,配合現代邏輯屬性(margin-block 等),能寫出精簡、可維護、跨語言友善的樣式碼。

copyright © 萬盛學電腦網 all rights reserved