常有讀者問我:一個 CSS 檔該怎麼組織,才能兼顧可讀性與後續維護?我的做法其實只有幾條簡單規則,但它們在面對設計複雜的頁面時確實能救命。以下用一個典型的「固定寬度雙欄」版型來示範。
把 body、a、form、input 這類基礎元素的設定放在檔案最開頭,是很值得維持的習慣。它們是整個頁面的基準,先定下來,後面的規則才有共同的起點。
/* -------------------------------
Html Elements
------------------------------- */
html { font-family: arial, verdana, sans serif; font-size: 13px; }
a:link, a:visited { color: #0033CC; }
a:hover { color: #003366; }
h1, h2, h3, h4, h5, h6,
form, input, textarea {
border: 0; padding: 0; margin: 0;
font-family: arial, verdana, sans serif;
}
h1 { font-size: 24px; color: #000000; }
h2 { font-size: 18px; color: #666666; }
...
為了讓程式碼好讀,我建議統一縮排,但要保留一點彈性:如果某個選擇器只有兩三個屬性(例如 #navbar),寫在同一行反而清爽;屬性一多(例如 #navbar li a:link),就該一個屬性一行,方便日後逐條比對與修改。
/* -------------------------------
PAGE Elements
------------------------------- */
#container { width: 780px; margin: 0 auto; }
#topbar { width: auto; display: block; height: 80px; }
#navbar { width: auto; display: block; height: 24px; }
#navbar ul, #navbar ul li { padding: 0; margin: 0; list-style: none; float: left; }
#navbar a { color: #FFFFFF; font-weight: bold; }
#navbar a:hover { background: #777777; }
#navbar li a:link,
#navbar li a:visited {
background: #444444;
text-decoration: none;
height: 24px;
line-height: 24px;
display: inline;
float: left;
width: auto;
padding: 0px 10px;
}
#main { width: auto; display: block; }
#column_left { width: 560px; margin-right: 20px; float: left; }
#column_right { width: 200px; float: left; }
div.spacer { clear: both; height: 10px; display: block; }
#footer { width: auto; display: block; height: 24px; }
#footer a { color: #666666; text-decoration: underline; }
這個段落刻意把「區塊骨架」與「區塊內的細節」分開:容器、頁首、導覽、主體、頁腳依序排列,讀的人順著頁面由上而下就能對應到程式碼位置。
檔案最後一段留給零散的客製 class,同樣沿用上面的規則——短的一行寫完,長的一個屬性一行。
/* -------------------------------
OTHER Class
------------------------------- */
.small { font-size: 11px; }
.underline { text-decoration: underline; }
div.small-section { background: #CCCCCC; }
div.small-section a { color: #333333; font-weight: bold; }
...
三段式結構(元素基準 → 頁面區塊 → 自訂 class)帶來的實際好處有三點:
誠實說,這些只是個人習慣,不是什麼硬性規範。但如果你曾經接手過一份上千行、毫無章法的樣式表,就會明白「可讀性」本身也是一種效能——它決定你三個月後還改不改得動這個專案。