樣式表寫久了會發現,屬性的排列順序其實會影響可讀性與維護成本。Mozilla 的開發文件裡流傳著一份建議順序,值得當成起點。
取自 mozilla.org 的 Base Styles,作者 fantasai:
/* Suggested order:
// 顯示屬性
* display
* list-style
* position
* float
* clear
// 自身屬性
* width
* height
* margin
* padding
* border
* background
// 文字屬性
* color
* font
* text-decoration
* text-align
* vertical-align
* white-space
* other text
* content
它的邏輯是「從外到內」:先決定這個元素在頁面上怎麼擺(顯示模式、定位、浮動),再決定它自己多大(尺寸、間距、邊框、背景),最後才是裡面的文字長什麼樣。
下表順序為從上到下、從左到右:
display ‖ visibility
list-style: list-style-type ‖ list-style-position ‖ list-style-image
position
top ‖ right ‖ bottom ‖ left
z-index
clear
float
width
max-width ‖ min-width
height
max-height ‖ min-height
overflow ‖ clip
margin: margin-top ‖ margin-right ‖ margin-bottom ‖ margin-left
padding: padding-top ‖ padding-right ‖ padding-bottom ‖ padding-left
outline: outline-color ‖ outline-style ‖ outline-width
border
background: background-color ‖ background-image ‖ background-repeat ‖ background-attachment ‖ background-position
color
font: font-style ‖ font-variant ‖ font-weight ‖ font-size ‖ line-height ‖ font-family
font: caption | icon | menu | message-box | small-caption | status-bar
text-overflow
text-align
text-indent
line-height
white-space
vertical-align
cursor
實務上還有一條約定俗成的補充:把 hack 放在最後。因為 hack 是例外,把例外集中在同一處,主線規則才讀得清楚。
以下語法屬於歷史文物,記錄於此僅供理解老舊程式碼:
.class {
background-color: #FFFF00; /* 所有瀏覽器 */
*background-color: #00FF00; /* IE */
_background-color: #00FFFF; /* IE6 */
}
/* 只有 Opera 認得 */
@media all and (min-width:0) {
.class { background-color: #FF00FF }
}
/* 同時鎖定 Opera 與 Safari */
@media all and (min-width:0) {
.class { background-color: #FF00FF }
html * .class { background-color: #808080 }
}
/* 僅 Firefox 3 與 IE7 認得 */
selector, x:-moz-any-link, x:default {
/* 規則寫在這裡 */
}
/* Chrome 的寫法 */
body:nth-of-type(1) p { color: #333333 }
/* IE8 beta1 專用 */
/*/ selector { … } /**/
上面這批 hack 在今天的專案裡一行都不該出現。星號前綴、底線前綴、以及靠語法錯誤觸發的解析差異,全是為了填補 IE6/7 時代的坑。現代瀏覽器的差異已經小到可以忽略,真的要處理跨瀏覽器問題,正確順序是:
@supports 做能力偵測。 判斷「瀏覽器是否支援某功能」,比判斷「瀏覽器是哪一個」可靠得多。@supports (display: grid) {
.layout { display: grid }
}
:where() 隔離。而屬性排序這件事,真正有價值的遺產不是那些 hack,而是「從外到內」的分組思路。養成這個習慣,你的樣式表會在無意間變得好讀——看到 position 就知道版面怎麼擺,往下幾行就能找到尺寸與間距。