萬盛學電腦網

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

CSS 註解最佳實務:打造可維護、團隊友善的樣式表

為什麼 CSS 註解很重要?

CSS 沒有變數、函式或模組系統(早期規格),隨著專案增長,樣式表極易變成「義大利麵代碼」。良好的註解能:

  • 建立目錄結構,快速定位區塊
  • 說明設計決策、Hack 原因、瀏覽器相容處理
  • 降低團隊溝通成本,新成員也能快速上手
  • 配合工具(如 stylelint、PostCSS)產生文件

頂層目錄註解範本

/*------------------------------------
  1. Reset & Normalize
  2. Variables & Tokens
  3. Base Styles (Typography, Links)
  4. Layout (Header, Footer, Grid)
  5. Components (Buttons, Cards, Forms)
  6. Utilities (Spacing, Visibility)
  7. Page-specific Overrides
  8. Media Queries (Responsive)
-----------------------------------*/

區塊標題註解風格

使用統一的視覺標記,方便編輯器摺疊/搜尋:

/*** Header ***/
#header { height: 145px; position: relative; }
#header h1 { width: 324px; margin: 45px 0 0 20px; float: left; height: 72px; }

/*** Content ***/
#content { background: #fff; width: 650px; float: left; min-height: 600px; overflow: hidden; }
#content h1 { color: #F00; } /* 設定字體顏色 */
#content .posts { overflow: hidden; }
#content .recent { margin-bottom: 20px; border-bottom: 1px solid #f3f3f3; position: relative; overflow: hidden; }

/*** Footer ***/
#footer { clear: both; padding: 50px 5px 0; overflow: hidden; }
#footer h4 { color: #b99d7f; font-family: Arial, Helvetica, sans-serif; font-size: 1.1em; }

行內說明註解

針對特定規則補充上下文:

.clearfix::after {
  content: "";
  display: table;
  clear: both;
  /* 修正浮動塌陷,支援 IE8+ */
}

@media (max-width: 768px) {
  .sidebar { display: none; }
  /* 行動版隱藏側欄,改由漢堡選單觸發 */
}

註解規範建議

  1. 統一風格:全專案採用同一種標題格式(如 `/*** Section ***/` 或 `/* Section ---- */`)。
  2. 英文或中文擇一:團隊共識優先,避免混雜造成搜尋困難。
  3. 說明「為什麼」而非「做什麼」:代碼已表達做什麼,註解補充業務邏輯、Bug 修正單號、設計稿連結。
  4. 標記待辦/已知問題:/* TODO: 重構為 Flexbox */、/* FIXME: IE11 flex bug */。
  5. 移除上線前註解:建構流程加入 cssnano 或 clean-css 自動清除,減少檔案體積。
  6. 現代工具輔助

    延伸閱讀

copyright © 萬盛學電腦網 all rights reserved