nth-child 和 nth-of-type 的區別 換個更合適的例子

nth-child 

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <style>
        span:nth-child(4),span:nth-child(7){  color:red;  }
        /*翻譯
         span 的父級元素的子元素第4個元素且是span的  所以span1紅了 
         span:nth-child(7)並未生效 因爲沒有匹配上
        */
        .t:nth-child(8){  color: blue;  }
        /*class 是t的父級元素的子元素第8個 且class有t 所以h2 2 藍了*/
    </style>
</head>

<body>
<h2 >我是h2 1</h2>
<p class="t">我是p 1</p>
<p class="t">我是p 2</p>
<span class="t">我是span1</span>
<span>我是span2</span>
<span class="t">我是span3</span>
<p class="t">我是p3</p>
<h2 class="t">我是h2 2</h2>
<h2 class="t">我是h2 3</h2>
</body>
</html>

 

nth-of-type

<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <style>
        span:nth-of-type(2),span:nth-of-type(4){  color:red;  }
        /*翻譯
         span 的父級元素的子元素中 類型是span的第二個和第四個  所以span2紅了 
         沒有第4個span 所以無效了
        */
        .t:nth-of-type(3){  color: blue;  }
        /*翻譯
         class 是t的父級元素的子元素中  各類型標籤的第3個 且有class="t"
         所以span3 p3 藍了  h2 3 沒有藍
        */
    </style>
</head>

<body>
<h2 >我是h2 1</h2>
<p class="t">我是p 1</p>
<p class="t">我是p 2</p>
<span class="t">我是span1</span>
<span>我是span2</span>
<span class="t">我是span3</span>
<p class="t">我是p3</p>
<h2 class="t">我是h2 2</h2>
<h2 >我是h2 3</h2>
</body>
</html>

希望對大家有幫助  感謝疫情

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