從新手到專業,這 15 條軍規覆蓋 CSS 編寫的核心最佳實踐,助你產出精簡、可維護、高效能的樣式表。
/* 冗長 */
border-top: 1px solid #ccc; border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc; border-left: 1px solid #ccc;
/* 精簡 */
border: 1px solid #ccc;
/* margin 顺序:上右下左 (順時針) */
margin: 10px 20px 30px 40px;
`width: 100px` ✅ | `width: 100` ❌。數值與單位間不加空格。
XHTML 區分大小寫,統一小寫避坑:`#header`、`.nav-item`、非 `#Header`/`.NavItem`。
div#content → #content
fieldset.details → .details
ID 唯一、類可複用,元素前綴累贅且限制復用。
* { margin: 0; padding: 0; box-sizing: border-box; }
消除瀏覽器差異,建立一致基線。
`color`、`font`、`line-height` 在 `body` 定義一次,子元素自動繼承。
p { color: #333; }
.update { color: #600; font-weight: bold; } /* 類選擇器更近,勝出 */
具體度計算:內聯 > ID > 類/屬性/偽類 > 標籤/偽元素。
<div class="box warning large">
.box { width: 200px; }
.warning { background: #fff3cd; border: 1px solid #ffc107; }
.large { padding: 20px; font-size: 1.2em; }
單元素多類組合,靈活復用。
/* 冗餘 */
#nav ul { } #nav li { } #nav a { }
/* 精簡 */
#nav { } #nav li { } #nav a { }
background: url(images/bg.png); /* ✅ */
background: url("images/bg.png"); /* ❌ 部分舊瀏覽器報錯 */
路徑相對 CSS 檔案位置,非 HTML。
h1, h2, h3, h4, h5, h6 {
font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
color: #333;
margin: 1em 0;
}
h1 { font-size: 2em; }
h2 { font-size: 1.6em; }
a:link { } a:visited { } a:hover { } a:active { }
記憶:LoVe HAte。若需 `:focus`,置於 `:hover` 前後視設計意圖而定。
.wrap { width: 960px; margin: 0 auto; }
body { text-align: center; } /* IE5/6 hack */
.wrap { text-align: left; } /* 修正內容對齊 */
@import "modern.css"; /* IE4 忽略 */
@import url("modern.css"); /* 兼容更廣 */
現代項目建議 `` + 媒體查詢替代。
💡 內化這 15 條,代碼質量將躍升專業級。