萬盛學電腦網

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

CSS 優化精簡十大技巧:從零值單位到速記屬性全攻略

為什麼要優化 CSS?

  • 減少檔案體積 → 更快下載、解析、渲染。
  • 提升可讀性、可維護性。
  • 強制統一團隊編碼風格。

十大精簡技巧速查表

1. 零值省略單位

/* ❌ */
padding: 10px 5px 0px 0px;
/* ✅ */
padding: 10px 5px 0 0;

0 不需單位,0px、0em、0% 皆為多餘。

2. 移除多餘選擇器

/* ❌ */
div#logo-wrap { ... }
/* ✅ */
#logo-wrap { ... }

ID 選擇器專一性極高,標籤前綴純屬贅餘,增加專一性風險。

3. 謹慎使用通配符 *

/* ❌ 污染全域 */
* { margin: 0; }

/* ✅ 限制範圍 */
#menu * { margin: 0; }

/* ✅ 現代重置用 :where() 降低專一性 */
:where(*) { margin: 0; }

4. Background 速記屬性

/* ❌ */
background-image: url(logo.png);
background-position: top center;
background-repeat: no-repeat;

/* ✅ */
background: url(logo.png) no-repeat top center;
/* 現代擴充 */
background: 
  linear-gradient(45deg, #fff, #f0f0f0) padding-box,
  url(pattern.png) repeat-x border-box,
  #fafafa content-box;

5. 顏色值縮寫

#000000 → #000
#336699 → #369
#ff0000 → #f00
/* 非成對不可縮寫:#010203, #abcdef */

6. Margin / Padding 合併與進階縮寫

/* 基礎合併 */
margin: 0 10px 0 10px;
/* 進階:上下相同、左右相同 */
margin: 0 10px;      /* 上下 0,左右 10px */
padding: 1rem 2rem;  /* 上下 1rem,左右 2rem */

7. Border 速記與單邊控制

/* 統一四邊 */
border: 1px solid #000;

/* 四邊不同寬度 */
border-width: 1px 2px 3px 4px;

/* 僅顯示右、下邊框(技巧) */
border: 1px solid #000;
border-width: 0 1px 1px 0;

8. Font 速記(順序嚴格)

/* ❌ 分散宣告 */
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 1em;
line-height: 150%;
font-family: "Microsoft JhengHei", sans-serif;

/* ✅ 一行搞定 */
font: italic small-caps bold 1em/150% "Microsoft JhengHei", sans-serif;

9. List-style 速記

list-style: square inside url(bullet.png);
/* type position image */

10. 合併相同屬性值的選擇器

/* ❌ */
h1 { color: #333; }
h2 { color: #333; }
h3 { color: #333; }

/* ✅ */
h1, h2, h3 { color: #333; }

自動化工具整合

  • Stylelint:規則 declaration-block-no-duplicate-properties、shorthand-property-no-redundant-values、color-hex-length。
  • cssnano:建構時自動執行上述所有優化。
  • Prettier:格式化統一風格(單引號、分號、縮排)。

優化前後實測

/* 原始 1.2KB */
.card { ... 30 行分散屬性 ... }

/* 優化後 0.4KB */
.card{background:#fff;border:1px solid #ddd;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,.1);color:#333;display:flex;flex-direction:column;font:1rem/1.5 system-ui,sans-serif;margin:1rem;padding:1.5rem;transition:box-shadow .2s}

體積減少 67%,Gzip 後更小。配合 HTTP/2 多路複用,效能提升顯著。

將這十大技巧內化為肌肉記憶,並納入團隊 Lint 規則,讓每一行 CSS 都精簡有力。更多 CSS 效能優化實戰,請關注本站工程化系列。

copyright © 萬盛學電腦網 all rights reserved