Rumah  >  Artikel  >  hujung hadapan web  >  CSS3中nth-child与nth-of-type的区别以及使用技巧

CSS3中nth-child与nth-of-type的区别以及使用技巧

php中世界最好的语言
php中世界最好的语言asal
2018-03-22 11:27:461990semak imbas

这次给大家带来CSS3中nth-child与nth-of-type的区别以及使用技巧,使用nth-child与nth-of-type的注意事项有哪些,下面就是实战案例,一起来看一下。

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>

结果如下:

上面这个例子,.demo li:nth-child(2)选择的是

  • one
  • 节点,而.demo li:nth-of-type(2)则选择的是
  • 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>

    结果:

    如上可见,在他们之前不指定标签类型,: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;
    }

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

    推荐阅读:

    css3的新属性box-sizing详解

    css3实现动画自行车效果

    Atas ialah kandungan terperinci CSS3中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