CSS3選取器中關於:nth-child和:nth-of-type區別的介紹

來源:互聯網
上載者:User

一、:nth-child

1.1 說明

:nth-child(n)選取器匹配屬於其父元素的第N個子項目,不論元素的類型。n可以是數字、關鍵詞或公式。

注意:如果第N個子項目與選擇的元素類型不同則樣式無效!

1.2 樣本

<style>p>p:nth-child(2){    color:red;}</style><p>    <p>我是第1個段落</p>    <p>我是第2個段落</p><!--符合條件:1、是<p>元素,2、父元素<p>的第二個元素。這裡被選擇,會變成紅色。-->    <p>我是第3個段落</p></p><p>    <p>我是第1個段落</p>    <span>我是第1個文本</span><!--不符合條件:不是<p>元素,沒有被選擇-->    <p>我是第2個段落</p></p>

1.3 改進

如果想讓上面第二個<span>生效的可以去除子項目<p>的選擇,寫一個父元素<p>加一個空格,以防止:nth-child不生效。

<style>p :nth-child(2){ //p+空格,只根據父元素選擇    color:red;}</style><p>    <p>我是第1個段落</p>    <span>我是第1個文本</span><!--符合條件-->    <p>我是第2個段落</p></p>

二、:nth-of-type

2.1 說明

:nth-of-type(n)選取器匹配屬於父元素的特定類型的第N個子項目的每個元素。n可以是數字、關鍵詞或公式。

2.2 樣本

<style>p>p:nth-of-type(2){    color:red;}</style><p>    <p>我是第1個段落</p>    <p>我是第2個段落</p><!--符合條件:1、是特定元素類型<p>,2、是父元素<p>的第二個<p>元素。這裡被選擇,會變成紅色-->    <p>我是第3個段落</p></p><p>    <p>我是第1個段落</p>    <blockquote>第1個引用</blockquote>    <p>我是第2個段落</p><!--符合條件:1、是特定元素類型<p>,2、是父元素<p>的第二個<p>元素。這裡被選擇,會變成紅色-->    <p>我是第3個段落</p></p>
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.