首頁 > web前端 > css教學 > 主體

關於CSS3中nth-child和nth-of-type的區別詳解

黄舟
發布: 2017-06-01 10:41:29
原創
1699 人瀏覽過

CSS3中nth-child與nth-of-type的差別其實很簡單::nth-of-type為什麼要叫:nth-of-type?因為它是以"type"來區分的。也就是說:ele:nth-of-type(n)是指父元素下第n個ele元素, 而ele:nth-child(n)是指父元素下第n個元素且這個元素為ele,若不是,則選擇失敗。

文字未免聽起來比較晦澀,便於理解,這裡附上一個小例子:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<style>
.demo li:nth-child(2){
color: #ff0000;
}
.demo li:nth-of-type(2){
color: #00ff00;
}
</style>
<body>
<p>
<ul class="demo">
<p>zero</p>
<li>one</li>
<li>two</li>
</ul>
</p>
</body>
</html>
登入後複製


結果如下:

關於CSS3中nth-child和nth-of-type的區別詳解

上面這個例子,.demo li:nth-child(2)選擇的是

  • one
  • 節點,而.demo li:nth-of-type(2)則選擇的是< ;li>two節點。

    但是如果在nth-child和 nth-of-type前不指定標籤呢?

    .demo :nth-child(2){
    color: #ff0000;
    }
    .demo :nth-of-type(2){
    color: #00ff00;
    }
    登入後複製


    這樣又會是什麼結果呢,請看html結構:

    <ul class="demo">
    <p>first p</p>
    <li>first li</li>
    <li>second li</li>
    <p>second p</p>
    </ul>
    登入後複製

    ##結果:


    關於CSS3中nth-child和nth-of-type的區別詳解
    如上可見,在他們之前不指定標籤類型,:nth-​​child(2) 選取依舊是第二個元素,無論它是什麼標籤。而:nth-type-of(2) 選取了兩個元素,分別是父級.demo中的第二個p標籤和第二個li標籤,由此可見,不指定標籤類型時,:nth-type -of(2)會選取所有類型標籤的第二個。

    我們已經了解了nth-child和nth-of-type的
    基本使用與區別,那麼更進一步nth-of-type(n)與nth-child(n)中的n是什麼呢?
    nth-of-type(n)與nth-child(n)中的n可以是數字、關鍵字或公式。 數字:也就是上面例子的使用,就不做贅述。 關鍵字:Odd 、even

    Odd 和even 是可用來匹配下標是奇數或偶數的子元素的關鍵字


    注意:第一個子元素的下標是1
    在這裡,我們為奇數和偶數p 元素指定兩種不同的背景色:

    p:nth-of-type(odd)
    {
    background:#ff0000;
    }
    p:nth-of-type(even)
    {
    background:#0000ff;
    }
    登入後複製

    公式:或者說是算術

    表達式
    使用公式(an + b)。描述:表示週期的長度,n 是計數器(從 0 開始),b 是偏移值。

    在這裡,我們指定了下標是3 的倍數的所有p 元素的背景色:

    p:nth-of-type(3n+0)
    {
    background:#ff0000;
    }
    登入後複製
    若是:nth-of-type(4n+2) 就是選擇下標是4的倍數加上2的所有元素



    總結


    以上是關於CSS3中nth-child和nth-of-type的區別詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    來源:php.cn
    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    熱門教學
    更多>
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板
    關於我們 免責聲明 Sitemap
    PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!