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>

 

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