DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS特效代碼
CSS 選擇器大全:標籤、屬性、偽類、偽元素與權重計算
編輯:CSS特效代碼     

一、基礎選擇器

標籤選擇器直接以 HTML 標籤名作為選取依據:

p { color: red; }

類別與 ID 選擇器則透過 class 與 id 屬性:

p { color: red; }
p.blue { color: blue; }
<p>這是一段紅色文字</p>
<p class="blue">這是一段藍色文字</p>

二、屬性選擇器

  • [attr^=val]:屬性值以 val 開頭
  • [attr$=val]:屬性值以 val 結尾
  • [attr*=val]:屬性值包含 val
/* data-role 以 h 開頭的 div */
div[data-role^=h] { color: red; }
/* data-role 以 content 結尾的 div */
div[data-role$=content] { color: blue; }
/* data-role 包含 foot 的 div */
div[data-role*=foot] { color: yellow; }
<div data-role="h-header">header</div>
<div data-role="c-content">content</div>
<div data-role="f-footer">footer</div>

三、偽類選擇器

以單一冒號開頭,用來選取某個位置或狀態下的元素:

/* 只有一個子元素的 ul 底下那個 li */
ul.test_only :only-child { background-color: red; }

li:first-child { color: red; }              /* 第一個子元素 */
li:last-child { color: orange; }            /* 最後一個子元素 */
li:nth-child(2n) { background-color: #ccc; }    /* 偶數項 */
li:nth-child(2n+1) { background-color: yellow; } /* 奇數項 */

*-of-type 系列則是「限定型別」的版本,例如 p:first-of-type 只選第一個 p:

dt:first-of-type { background-color: #ccc; }
dt:last-of-type { background-color: red; }
dd:nth-of-type(3) { background-color: orange; }
dd:nth-last-of-type(3) { background-color: yellow; }

四、偽元素選擇器

以雙冒號開頭,操作的是元素內部的某個片段或插入的內容:

div.oth-class p::first-letter { font-size: 25px; font-weight: bold; }
div.oth-class p::first-line { color: red; }
div.oth-class p::before { content: "before"; }
div.oth-class p::after { content: "after"; }
div.oth-class p::selection { background-color: #ccc; color: orange; }

要留意的是,::before 與 ::after 插入的內容屬於生成內容,無法被滑鼠選取複製。

五、權重計算

CSS 用一組四元數來衡量選擇器的優先程度:

  • a = 行內樣式的數量
  • b = ID 選擇器的數量
  • c = 類別、偽類、屬性選擇器的數量
  • d = 標籤選擇器與偽元素選擇器的數量

權重依序為 1000、100、10、1,最終值 = a×1000 + b×100 + c×10 + d。

疊加規則:同屬性時高權重覆蓋低權重,權重相同則後者覆蓋前者;不同屬性則是合併呈現。另外,明確指定的屬性永遠優先於從父元素繼承而來的值。

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