萬盛學電腦網

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

CSS 代碼規範 11 大原則:可維護、高效能、團隊協作

1. 使用 Reset / Normalize,但非通用選擇器

/* 不推薦 */
* { margin:0; padding:0; }

/* 推薦:Normalize.css 或精簡 Reset */
body, h1, h2, h3, h4, h5, h6, p, ul, ol, li, form, fieldset, legend, button, input, textarea, th, td, img {
  margin:0; padding:0; border:0;
}
ul, ol { list-style:none; }
a { text-decoration:none; color:inherit; }
img { vertical-align:middle; }
table { border-collapse:collapse; border-spacing:0; }

2. 語義化命名 (避免表現類命名)

/* 差 */ .red-btn { background:red; } .left-bar { float:left; }
/* 好 */ .btn-primary { } .sidebar { }

命名基於**內容/功能**,而非顏色/位置/大小。固定工具類 (如 .clearfix, .text-center) 除外。

3. 充分利用簡寫屬性

/* 縮寫前 */
li { font-family:Arial; font-size:1.2em; line-height:1.4em; padding-top:5px; padding-bottom:10px; padding-left:5px; }

/* 縮寫後 */
li { font:1.2em/1.4em Arial, sans-serif; padding:5px 0 10px 5px; }

常用簡寫:margin, padding, border, font, background, flex, grid。

4. 善用 CSS 繼承減少重複

/* 差 */
.container li, .container p, .container h1 { font-family:Georgia, serif; }

/* 好 */
.container { font-family:Georgia, serif; } /* 子元素自動繼承 */

5. 合併共同樣式的選擇器 (多重選擇器)

/* 差 */
h1 { font-family:Arial; font-weight:normal; }
h2 { font-family:Arial; font-weight:normal; }
h3 { font-family:Arial; font-weight:normal; }

/* 好 */
h1, h2, h3 { font-family:Arial; font-weight:normal; }

6. 結構化註釋與目錄

/*------------------------------------
  1. Reset & Base
  2. Layout (Header, Content, Sidebar, Footer)
  3. Components (Buttons, Cards, Forms)
  4. Utilities
------------------------------------*/

/*** 2.1 Header ***/
.header { ... }

/*** 2.2 Content ***/
.content { ... }
  .content .post { ... }

7. 屬性聲明按字母排序 (或邏輯分組)

.card {
  background:#fff;
  border-radius:8px;
  box-shadow:0 2px 8px rgba(0,0,0,.1);
  color:#333;
  display:flex;
  flex-direction:column;
  margin:1rem;
  padding:1.5rem;
  width:100%;
}

字母序利於查找、Diff 乾淨;團隊可約定「佈局→盒模型→視覺→字體→其他」邏輯分組。

8. 保持可讀性:每行一屬性

/* 推薦 */
.card {
  background:#fff;
  border-radius:8px;
}

/* 避免單行 (屬性>3時) */
.card{background:#fff;border-radius:8px;box-shadow:...}

9. 選擇更高效的屬性值

  • border:none 優於 border:0 (不計算 color/style)
  • display:none 優於 visibility:hidden (不佔空間、不渲染)
  • opacity:0 + pointer-events:none 替代 visibility:hidden 需互動時

10. 用 <link> 替代 @import

  • @import 阻塞平行下載、舊瀏覽器不支援、非 HTML 標準。
  • 建置工具 (Vite, Webpack, PostCSS) 合併 CSS,生產環境只輸出 <link>。

11. 外部樣式表 + 長期快取

  • HTML 內聯 CSS 每次請求都下載;外部 CSS 可快取、CDN 分發、瀏覽器預載。
  • 檔名加雜湊:style.a1b2c3.css,Cache-Control: max-age=31536000, immutable。
  • 關鍵 CSS 內聯首屏,其餘 <link rel="preload" as="style" onload="this.rel='stylesheet'"> 異步載入。

工具鏈落地

  • Lint: Stylelint (規則集 stylelint-config-standard + 自訂命名規則)
  • Format: Prettier (統一縮排、引號、分號)
  • CI: Git Hook (Husky) + CI Pipeline 強制通過才能合併
copyright © 萬盛學電腦網 all rights reserved