CSS3 為我們帶來了一批強大的結構偽類選擇器,讓定位元素變得更加精準靈活。以下整理了常用的幾個:
:first-of-type p:first-of-type 選中屬於其父元素首個 <p> 的每個 <p> 元素。 :last-of-type p:last-of-type 選中屬於其父元素最後一個 <p> 的每個 <p> 元素。 :only-of-type p:only-of-type 選中屬於其父元素唯一 <p> 的每個 <p> 元素。 :only-child p:only-child 選中屬於其父元素唯一子元素的每個 <p> 元素。 :nth-child(n) p:nth-child(2) 選中屬於其父元素第二個子元素的每個 <p> 元素。 :nth-last-child(n) p:nth-last-child(2) 同上,但從最後一個子元素開始計數。 :nth-of-type(n) p:nth-of-type(2) 選中屬於其父元素第二個 <p> 的每個 <p> 元素。 :nth-last-of-type(n) p:nth-last-of-type(2) 同上,但從最後一個子元素開始計數。 :last-child p:last-child 選中屬於其父元素最後一個子元素的每個 <p> 元素。 :root :root 選中文檔的根元素。 :empty p:empty 選中沒有子元素(含文本節點)的每個 <p> 元素。 :target #news:target 選中當前活動的 #news 元素。 :enabled input:enabled 選中每個啟用的 <input> 元素。 :disabled input:disabled 選中每個禁用的 <input> 元素。 :checked input:checked 選中每個被選中的 <input> 元素。 :not(selector) :not(p) 選中每個非 <p> 元素。 ::selection ::selection 選中被使用者選取的元素部分。