Rumah  >  Artikel  >  hujung hadapan web  >  选择器nth-child和:nth-of-type的使用详解

选择器nth-child和:nth-of-type的使用详解

php中世界最好的语言
php中世界最好的语言asal
2018-03-21 11:17:462104semak imbas

这次给大家带来选择器nth-child和:nth-of-type的使用详解,使用选择器nth-child和:nth-of-type的注意事项有哪些,下面就是实战案例,一起来看一下。

先看一个简单的实例,首先是HTML部分:

<section>
    <p>我是第1个p标签</p>
    <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
</section>

然后两个选择器相对应的CSS代码如下:

p:nth-child(2) { color: red; }
p:nth-of-type(2) { color: red; }

上面这个例子中,这两个选择器所实现的效果是一致的,第二个p标签的文字变成了红色:

尽管上面两个demo的最后效果一致,但是两个选择器之间存在差异是必然的。

对于:nth-child选择器,在简单白话文中,意味着选择一个元素:

1、这是个段落元素
2、这是父标签的第二个孩子元素

对于:nth-of-type选择器,意味着选择一个元素:

1、选择父标签的第二个段落子元素

我们把上面的实例稍作修改,就可以看到这两个选择器之间的差异表现了,如下HTML代码:

<section>
    <p>我是一个普通的p标签</p>
    <p>我是第1个p标签</p>
    <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
</section>

还是与上面例子一致的CSS测试代码:

p:nth-child(2) { color: red; }

p:nth-of-type(2) { color: red; }

这时候两个选择器所渲染的结果就不一样了。

p:nth-child(2)其渲染的结果不是第二个p标签文字变红,而是第一个p标签,也就是父标签的第二个子元素。

p:nth-of-type(2)的表现显得很坚挺,其把希望渲染的第二个p标签染红了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

css3的pointer-events使用详解

focus-within的使用详解

Atas ialah kandungan terperinci 选择器nth-child和:nth-of-type的使用详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:css3的pointer-events使用详解Artikel seterusnya:动画TAB切换怎样实现