CSS 屬性順序看似小事,但當樣式表越來越長,一致的書寫順序能大幅提升可讀性。它能讓維護者快速找到版面、框模型、背景與文字相關設定,也能減少屬性遺漏。
建議先寫 display、visibility、list-style、position 等與元素角色和定位有關的屬性。接著再寫 top、right、bottom、left、z-index、clear、float 等定位與浮動設定。
尺寸相關屬性可放在定位之後,例如 width、max-width、min-width、height、max-height、min-height。接著是 overflow、margin、padding、outline 與 border。
這一段通常決定元素的外部尺寸與內部間距,是版面是否正確的關鍵。
背景可放在邊框之後,例如 background-color、background-image、background-repeat、background-attachment、background-position。文字相關屬性則可放在最後,例如 color、font、text-align、text-indent、line-height、white-space、vertical-align 與 cursor。
一個可參考順序如下:
display visibility list-style position top right bottom left z-index clear float width height overflow margin padding outline border background color font text-align line-height cursor
順序不是硬性標準,團隊可依需求調整。重點是全體成員使用同一套規則,讓 CSS 從「能跑就好」變成「易讀、易改、易維護」。