css nth-of-type 奧祕

:nth-of-type(n) 選擇器匹配屬於父元素的特定類型的第 N 個子元素的每個元素.。出處來源:https://www.w3school.com.cn/cssref/selector_nth-of-type.asp

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #test .test:nth-of-type(2) {
            color: red;
        }
    </style>
</head>

<body>

    <div id="test">
        <p class="test">123</p>
        <div class="test">12312</div>
        <div class="test">12312</div>
        <p class="test">123</p>
    </div>
</body>

</html>

結果是

 理解: 

  nth-of-type:  1.先匹配 元素   2匹配類名
 也就是 

#test p.test:nth-of-type(2) {

  color: red;
}

#test div.test.nth-of-type(2) {

  color: red;
}

 

如果出現只匹配元素,沒有匹配類名,則會出現下面這個情況:

<!DOCTYPE html>
<html>
<head>
<style> 
.aa:nth-last-of-type(1)
{
background:#ff0000;
}
</style>
</head>
<body>

<h1>這是標題</h1>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p>第四個段落。</p>
<p class="aa">第五個段落。</p>
<p>45454</p>
</body>
</html>

結果是:

   

  爲什麼會不見了,這時候我們設置成這樣測試

<!DOCTYPE html>
<html>
<head>
<style> 
.aa:nth-last-of-type(1)
{
background:#ff0000;
}
</style>
</head>
<body>

<h1>這是標題</h1>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p>第四個段落。</p>
<p class="aa">第五個段落。</p>
<p class="aa">45454</p>
</body>
</html>

 結果是: 

   

   這樣我們就能得出一個猜想,說明nth-of-type匹配的時候必須元素和類名全部都要匹配,意味着上面應該改成

<!DOCTYPE html>
<html>
<head>
<style> 
.aa:nth-last-of-type(2)
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>這是標題</h1>
<p>第一個段落。</p>
<p>第二個段落。</p>
<p>第三個段落。</p>
<p>第四個段落。</p>
<p class="aa">第五個段落。</p>
<p>45454</p>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章