跳到主要內容

不同瀏覽器不一致的樣式表預設值

有許多 Browsers,不同 Browser 內定的樣式表都有其預設值,在設計網頁時,對於不同 Browsers 之間,可能就需要為不同 Browsers 設計不同的 CSS ,這樣讓網頁設計者相當困擾,一般的做法是將不同 Browsers 內定的樣式表預設值 Reset,Reset 之後才設計元件的 CSS,這樣設計出來的 CSS,使用不同 Browsers 觀看,就會有相同的效果。

目前網路上常被使用 Reset 樣式表預設值的套件有:
樣式表有優先順序,其寫法上的優先順序為:[1]

  1. Client user defined style
  2. Embedded or inline style sheet 
  3. Internal style sheet
  4. External style sheet
  5. Browser default style(Client User browser)
按照 CSS Selector 來區別優先順序,在 CSS 2.1 Section 6.4.3:[2]中寫道:
A selector's specificity is calculated as follows:
  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)
  • The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
Some examples:
 *             {}  /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
 li            {}  /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
 li:first-line {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul li         {}  /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
 ul ol+li      {}  /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
 h1 + *[rel=up]{}  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
 ul ol li.red  {}  /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
 li.red.level  {}  /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
 #x34y         {}  /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
 style=""          /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */
 
<HEAD>
<STYLE type="text/css">
  #x97z { color: red }
</STYLE>
</HEAD>
<BODY>
<P ID=x97z style="color: green">
</BODY>
 
In the above example, the color of the P element would be green. The declaration in the "style" attribute will override the one in the STYLE element because of cascading rule 3, since it has a higher specificity.

------------------------------------------------
[1] http://www.plus2net.com/html_tutorial/css-types.php
[2] https://www.w3.org/TR/CSS2/cascade.html#specificity

留言