DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
CSS 撰寫順序的建議:Firefox 專案的排序慣例與瀏覽器 Hack
編輯:CSS詳解     

樣式表寫久了會發現,屬性的排列順序其實會影響可讀性與維護成本。Mozilla 的開發文件裡流傳著一份建議順序,值得當成起點。

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 是例外,把例外集中在同一處,主線規則才讀得清楚。

舊時代的瀏覽器 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 時代的坑。現代瀏覽器的差異已經小到可以忽略,真的要處理跨瀏覽器問題,正確順序是:

  1. 先寫標準語法。 大多數「IE 有問題」的狀況,換成 flex 或 grid 就自動消失了。
  2. 用 @supports 做能力偵測。 判斷「瀏覽器是否支援某功能」,比判斷「瀏覽器是哪一個」可靠得多。
  3. @supports (display: grid) {
      .layout { display: grid }
    }

  4. 真的需要針對特定瀏覽器時,才動用廠商前綴或 :where() 隔離。

而屬性排序這件事,真正有價值的遺產不是那些 hack,而是「從外到內」的分組思路。養成這個習慣,你的樣式表會在無意間變得好讀——看到 position 就知道版面怎麼擺,往下幾行就能找到尺寸與間距。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved