Css nth-of-type() 结构参数类

久伴 2019年9月22日16:22:59 评论 82

nth-of-type()和nth-child()区别

以下放出二个结构类的代码及运行结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nth-child</title>
    <style>
       div:nth-child(2) {
            color: red;
        }
    </style>
</head>
<body>
<ul>
    <div>1</div>
    <p>2</p>
    <div>3</div>
    <section>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
    </section>
</ul>
</body>
</html>

nth-child(2) 基于body下面的第一个是div但是不满足条件,基于第二个是p 所以body标签内section标签外无div发生变化,section标签中第二个div是基于section标签所以会发生变化,所以2会变红

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nth-child</title>
    <style>
       div:nth-of-type(2) {
            color: red;
        }
    </style>
</head>
<body>
<ul>
    <div>1</div>
    <p>2</p>
    <div>3</div>
    <section>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
    </section>
</ul>
</body>
</html>

nth-of-type(2) 基于body寻找第二个div,第一个是div匹配不上,第二个是p不符合of-type条件,继续匹配,相当于空气,第三个div相当于第二个,匹配成功,由此可见 3 2会变红

久伴

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: