nth-of-type
nth-of-type與nth-child
對於:nth-child選擇器,在簡單白話文中,意味著選擇一個元素如果:
- 這是個段落元素
- 這是父標籤的第二個孩子元素
對於:nth-of-type選擇器,意味著選擇一個元素如果:
- 選擇父標籤的第二個段落子元素
下面例項就可以看到這兩個選擇器之間的差異表現了,如下HTML程式碼:
<section> <div>我是一個普通的div標籤</div> <p>我是第1個p標籤</p> <p>我是第2個p標籤</p><!-- 希望這個變紅 --> </section>
CSS測試程式碼:
p:nth-child(2) { color: red; } p:nth-of-type(2) { color: red; }
p:nth-child(2)渲染的結果不是第二個p標籤文字變紅,而是第一個p標籤,也就是父標籤的第二個子元素。如下效果截圖:
p:nth-of-type(2)的表現顯得很堅挺,其把希望渲染的第二個p標籤染紅了,如下截圖:

nth-of-type與類
參考: ofollow,noindex" target="_blank">https://stackoverflow.com/questions/6447045/css3-selector-first-of-type-with-class-name
It's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; } .myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
Explanations and illustrations for the workaround are given here and here .