以下內容參考了業界規範與主流趨勢,把 CSS 開發中該注意的細節與效能問題做了一次完整梳理,值得收藏起來當作對照表。

瀏覽器必須等所有樣式表載入完成才能開始渲染頁面,在此之前畫面會是一片空白。因此樣式表要放在 head 裡。而 @import 的效果相當於把樣式表連結放到頁面底部,從效能角度請避免使用。
Expression 只有 IE 支援,而且它的執行頻率遠比多數人想像的高:頁面渲染與 resize 時會跑,捲動時會跑,連滑鼠在頁面上移動都會跑。加個計數器就能發現,隨便滑一下滑鼠,執行次數就會破萬。
十六進位顏色值:
/* 不建議 */ color: #eebbcc; /* 建議 */ color: #ebc;
屬性值:
margin-top: 2px; margin-right: 5px; margin-bottom: 2em; margin-left: 15px; → margin: 2px 5px 2em 15px; border-width: 1px; border-style: solid; border-color: #000; → border: 1px solid #000; font-style: italic; font-variant: small-caps; font-weight: bold; font-size: 1em; line-height: 140%; font-family: sans-serif; → font: italic small-caps bold 1em/140% sans-serif; background-color: #f00; background-image: url(background.gif); background-repeat: no-repeat; background-attachment: fixed; background-position: 0 0; → background: #f00 url(background.gif) no-repeat fixed 0 0; list-style-type: square; list-style-position: inside; list-style-image: url(image.gif); → list-style: square inside url(image.gif);
/* 冗長寫法 */
.class1 { position: absolute; left: 20px; top: 30px; }
.class2 { position: absolute; left: 20px; top: 30px; }
/* …以下略 */
/* 合併寫法 */
.class1, .class2, .class3, .class4, .class5, .class6 {
position: absolute; left: 20px; top: 30px;
}
<!-- 不建議 --> <A HREF="/">Home</A> <!-- 建議 --> <a href="/">Home</a>
<!-- 不建議 --> <p>What? _</p> <!-- 建議 --> <p>Yes please.</p>
HTML:<meta charset="utf-8"> CSS: @charset "utf-8";
<!DOCTYPE html>
上線前用 W3C 的驗證工具跑一遍,能提前攔下不少低級錯誤。
<!-- 不建議:用 div 假裝連結 --> <div onclick="goToRecommendations();">All recommendations</div> <!-- 建議 --> <a href="recommendations/">All recommendations</a>
<!-- 不建議 --> <img src="spreadsheet.png"> <!-- 建議 --> <img src="spreadsheet.png" alt="Spreadsheet screenshot.">
<!-- 不建議 --> The currency symbol for the Euro is "&eur;". <!-- 建議 --> The currency symbol for the Euro is "€".
/* 不建議:無意義 */ #yee-1901 {}
/* 不建議:描述外觀 */ .button-green {} .clear {}
/* 建議:具體 */ #gallery {} #login {} .video {}
/* 建議:通用 */ .aux {} .alt {}
margin: 0; padding: 0;
font-size: .8em;
遇到相容問題時,先試著換一種解法,而不是急著塞 hack。
省略最後一個分號雖然能省一個位元組,但非常不利於團隊維護,得不償失。
/* 不建議 */ .test { display: block; height: 100px }
/* 建議 */ .test { display: block; height: 100px; }
瀏覽器是「從右往左」解析選擇器的。對於:
#god > li { font-weight: bold; }
瀏覽器會先找出頁面上所有 li 節點,再逐一檢查其父節點的 id 是否為 god。由此可知,選擇器匹配遠比我們想像的慢,CSS 效能問題不容忽視。
#toc li { font-weight: bold; }
這個效率比子選擇器更差,而且要差很多。瀏覽器會遍歷所有 li 節點,然後一層層往上找父節點直到文件根節點,找到 id 為 toc 的才匹配成功,否則換下一個 li 繼續找。
[hidden="true"] { ... } /* 通用規則 */
這條規則要求遍歷頁面上「所有」節點,逐一檢查是否有 hidden 屬性且值為 true。這是最耗時的匹配形式,應盡量避免。星號也一樣:
#god li *
它會先找出頁面上所有元素,再篩出祖先包含 li 的,然後再檢查父元素 id 是否為 god。
全域選擇器唯一推薦的用法,是統一的樣式重置:
* { margin: 0; padding: 0; }
button#goButton { ... } → #goButton {}
.fundation#testIcon { ... } → #testIcon {}
button.indented { ... } → .button-indented { ... }
工程師常會在 class 前加上標籤名稱,想更精準地定位節點,但這樣效率往往更差。因為 class 在全域範圍內本就應該唯一,用唯一的 class 名稱定位比組合定位更快。這麼做還能避免「頁面元素標籤被改掉,樣式就跟著失效」的問題,真正做到樣式與結構分離、各自獨立維護。
可以考慮把層級關係寫進一個 class 裡,代價是層級變動時改起來比較麻煩:
span[mailfolder="true"] > table > tr > td.columnClass { ... }
→ .span-mailfolder-tbl-tdCol { ... }
可以適度縮寫:
ocHeroImage → oc-HeroImage → heroImg
若覺得縮寫難懂,可以加連字符或註解輔助。但基本上,命名還是短一些好,只要容易辨認即可。
原因有三:有空格的檔名會被當成兩個關鍵字;有空格就不能省略引號,多兩個位元組;空格會被瀏覽器轉成 %20,舊瀏覽器可能不支援,而硬寫進 URL 的話每個參照都多兩個字元。
input { background: url("/images/shadow background.gif"); }
@import url(//www.google.com/css/go.css);
treehead treerow treecell { ... } → treehead > treerow > treecell { ... }
後代選擇器是相對耗時的選擇器,能用子選擇器替代時就應該替代。
color、font、letter-spacing、line-height、list-style、text-align、text-indent、text-transform、white-space、word-spacing 等屬性都會被繼承,寫在父元素上一份即可:
#bookmark > .menu-left { list-style-image: url(blah); }
→ #bookmark { list-style-image: url(blah); }
可用 YUI Compressor 或類似工具壓縮後再上線。
同時能避開混合內容(mixed content)問題並縮減檔案大小:
<!-- 不建議 --> <script src="https://www.google.com/js/gweb/analytics/autotrack.js"></script>
<!-- 建議 --> <script src="//www.google.com/js/gweb/analytics/autotrack.js"></script>
/* 不建議 */ .example { background: url(https://www.google.com/images/example); }
/* 建議 */ .example { background: url(//www.google.com/images/example); }
HTML5 規範指定了一些可以省略的標籤,能縮減檔案大小:
<!-- 不建議 --> <!DOCTYPE html> <html> <head><title>Spending money, spending bytes</title></head> <body><p>Sic.</p></body> </html> <!-- 建議 --> <!DOCTYPE html> <title>Saving money, saving bytes</title> <p>Qed.
圖片等資源通常只有 CSS 會用到,把圖片資料夾放在 CSS 檔的同一層目錄,就能使用相對路徑,省下位元組:
input { background: url("images/shadow background.gif"); }
慣例上資料夾會用資源的複數形(images、assets、fonts),但其實單數形(img、asset、font)也完全夠用,而且能省下不少位元組。以這段 58 位元組的程式碼為例:
input { background: url("/images/shadow background.gif"); }
優化後變成 52 位元組,約 10% 的壓縮:
input { background: url(img/shadow-background.gif); }
再用上縮寫可以進一步縮減:
input { background: url(img/shadow-bg.gif); }
一個專案若有幾百行這樣的程式碼,累積下來就是幾百個位元組;對超大流量的站點而言,這是相當可觀的頻寬節省。
去掉末尾分號能省位元組,但不利維護。合理的折衷是:開發階段保留,壓縮發布階段移除。
.clear { clear: both; } → .clear { clear: both }
background-color: blue; → background: blue;
但要謹慎使用——簡寫中被省略的屬性會取預設值,可能把前面已設定的屬性覆蓋掉。
filter 適用於 IE8 以下,-ms-filter 適用於 IE9 以上。YUI 會把它壓縮成:
selector {
-ms-filter: "alpha(opacity=65)";
filter: alpha(opacity=65);
}
由於 YUI 廣泛使用且社群經過深度測試,這種寫法可以放心採用。
Google 建議按字母順序書寫 CSS 規則以便維護,其他公司也有各自的規範。但從 Gzip 壓縮的角度看,重點其實是「整份文件的書寫順序保持一致」,這樣才能提高壓縮率。
background: fuchsia; border: 1px solid; -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; color: black; text-align: center; text-indent: 2em;
檔案可以適度合併,只保留基本層級即可:
<link rel="stylesheet" href="https://css.somedomain.com/reset.css" type="text/css" /> <link rel="stylesheet" href="https://css.somedomain.com/global.css" type="text/css" /> <link rel="stylesheet" href="https://css.somedomain.com/home.css" type="text/css" />
這份清單裡的項目並非每一條都同等重要。真正影響使用者體驗的,通常是前幾條:樣式表放對位置、選擇器不要寫得太深、避免全域選擇器、上線前壓縮。剩下的位元組級優化,則是在這些都做對之後才值得花力氣的部分。此外,這份清單成形於 2012 年前後,其中關於 IE 濾鏡、CSS Expression、廠商前綴的建議在今天多數已無必要;但「選擇器效率」「避免深層後代選擇器」「善用繼承」「上線前壓縮」這幾條,放到現在依然是好習慣。