萬盛學電腦網

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

CSS 屬性排序與格式化規範:打造一致可維護的樣式表

為何需要屬性排序規範?

隨意的屬性順序會導致:Diff 噪音大、審查困難、合併衝突頻發。統一排序規範是團隊協作基石。

主流排序策略對比

策略優點缺點適用場景
功能分組語義清晰、易尋找相關屬性需記憶分組順序大型團隊、長期專案
字母序機械化、工具易實現、無爭議語義割裂(如 margin 分散)自動化程度高、CI 整合
濃度序佈局優先、符合渲染順序定義模糊、主觀性強個人偏好、小型專案

推薦:功能分組序(業界主流)

.card {
  /* 1. 佈局與定位 */
  display: flex;
  position: relative;
  z-index: 10;
  
  /* 2. 盒模型 */
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  padding: 24px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  box-sizing: border-box;
  
  /* 3. 視覺樣式 */
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  /* 4. 字體與文字 */
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  font-size: 16px;
  line-height: 1.5;
  color: #333;
  
  /* 5. 互動與動畫 */
  transition: box-shadow 0.3s ease, transform 0.2s ease;
}

.card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

選擇器排序原則

  1. 元素選擇器 → 類別選擇器 → ID 選擇器 → 偽類/偽元素
  2. 父選擇器在前,子選擇器在後(符合瀏覽器解析順序)
  3. 通用/重置樣式在檔案最前

自動化落地

/* .stylelintrc.json */
{
  "plugins": ["stylelint-order"],
  "rules": {
    "order/order": [
      "custom-properties",
      "dollar-variables",
      "declarations"
    ],
    "order/properties-order": [
      "display", "position", "top", "right", "bottom", "left", "z-index",
      "flex", "flex-*", "grid", "grid-*",
      "width", "min-width", "max-width", "height", "min-height", "max-height",
      "margin", "margin-*", "padding", "padding-*",
      "border", "border-*", "border-radius",
      "background", "background-*",
      "color", "font", "font-*", "line-height", "text-*",
      "opacity", "transform", "transition", "animation"
    ],
    "order/alphabetical": false
  }
}
copyright © 萬盛學電腦網 all rights reserved