Skip to content

CSS Performance - 檔案最小化

檔案最小化 (Minification) 是移除源碼中的空白、註解、換行等。

移除不必要的內容

移除空白字元

原始

css
.btn {
  color: red;
  
  background: blue;
}

最小化

css
.btn{color:red;background:blue}

移除註解

原始

css
/* 按鈕基礎樣式 */
.btn {
  /* 文字顏色 */
  color: #333;
  /* TODO: 修改背景色 */
  background: #fff;
}

最小化

css
.btn{color:#333;background:#fff}

移除最後的分號

原始

css
.header {
  margin: 0;
  padding: 0;
}

最小化

css
.header{margin:0;padding:0}

小工具

安裝 Minifier 套件後,可在未開啟的檔案上或已開啟的檔案中,按 滑鼠右鍵 -> Minify,即可產生最小化的檔案,檔案的名稱特徵為 檔名.min.css

縮寫優化

這部分內容在 前篇文章 有詳細解說,請移駕至此觀看 縮寫表示法!

選取器優化

移除重複選擇器

原始

css
.btn, .button {
  color: blue;
}
.btn, .button {
  background: white;
}

最小化

css
.btn,.button{color:blue;background:white}

合併規則

原始

css
h1 { font-size: 2em; }
h1 { color: blue; }
h1 { margin: 0; }

最小化

css
h1{font-size:2em;color:blue;margin:0}