为了账号安全,请及时绑定邮箱和手机立即绑定

nth of-type vs nth-child

nth of-type vs nth-child

眼眸繁星 2019-07-08 12:44:15
nth of-type vs nth-child我有点困惑于第n个类型的伪类,以及它应该如何工作-特别是与第n个子类相比。也许我想错了,但考虑到这个结构<div class="row">     <div class="icon">A</div>     <div class="icon">B</div>     <div class="label">1</div>     <div class="label">2</div>     <div class="label">3</div></div>.第三个子元素(带有类标签的第一个元素)应该(也许?)可供选择.row .label:nth-of-type(1) {     /* some rules */}但是,至少在这里的铬,它没有选择它。它似乎只有当它是第一个孩子在行,这是相同的第n个孩子-因此,这和第n类型之间有什么区别?
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

这个nth-child伪类指的是“N个匹配的子元素”,意思是如果您有如下结构:

<div>
    <h1>Hello</h1>

    <p>Paragraph</p>

    <p>Target</p></div>

然后p:nth-child(2)将选择也是p的第二个子级(即p加上“段”)。
p:nth-of-type将选择第二个匹配p元素,(即我们的目标)p).

以下是ChrisCoyier@cs-Tricks.com关于这一主题的一篇伟大文章


您的类型中断的原因是类型指元素的类型(即,div),但是第一个div与您提到的规则不匹配(.row .label),因此该规则不适用。

原因是css从右向左解析。,这意味着浏览器首先在:nth-of-type(1),确定它搜索类型的元素。div,这也是它的第一个类型,它与.row元素,以及第一个元素,.icon元素。然后,它将读取元素应该具有.label类,它与上述任何内容都不匹配。

如果要选择第一个Label元素,则需要将所有标签包装在它们自己的容器中,或者只需使用nth-of-type(3)(假设总是有两个图标)。

另一种选择(可悲的是)是使用.等着吧.。jQuery:

$(function () {
    $('.row .label:first')
        .css({
            backgroundColor:"blue"
        });});


查看完整回答
反对 回复 2019-07-08
?
胡说叔叔

TA贡献1804条经验 获得超8个赞

.label:nth-of-type(1)

此处“type”指的是元素的类型。在这种情况下,div不是去上课。这并不意味着第一个元素是.label,相反,它意味着其类型的第一个元素也有一个label.

类没有任何元素。label在索引处1他们那种类型的。


查看完整回答
反对 回复 2019-07-08
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

在图中添加的10个元素中,有8个是<p>和2<i>,两个阴影部分元素指示<i>其余8个是<p>

该页面的CSS位于以下位置:

<style>
    * {
        padding: 0;
        margin:0;
    }
    section p {
        width: 20px;
        height: 20px;
        border:solid 1px black;
        border-radius: 15px;
        margin:20px;
        float: left;
    }
    section i {
        width: 20px;
        height: 20px;
        border:solid 1px black;
        border-radius: 15px;
        margin:20px;
        float: left;
    }
   section p:nth-child(1) {
        background-color: green; /*first-child of p in the flow*/
    }
   section i:nth-child(1) {
        background-color: red;  /*[first-child of i in the flow]NO */
    }
   section i:nth-of-type(1) {
        background-color: blue;  /*the type i of first child in the flow*/
    }
    </style></head><body>

    <section>
        <p></p>
        <p></p>
        <p></p>
        <p></p>
        <i></i>
        <p></p>
        <i></i>
        <p></p>
        <p></p>
        <p></p>
    </section></body>

第一个绿色灯泡表示

 section p:nth-child(1) {
                background-color: green; /*first-child of p in the flow*/
            }

代码中的第二个红色灯泡不起作用,因为我不是流中的第一个元素。

section i:nth-child(1) {
            background-color: red;  /*[first-child of i in the flow]NO */
        }

图中的蓝色灯泡表示流动中的第一种类型的i。

section i:nth-of-type(1) {
            background-color: blue;  /*the type i of first child in the flow*/
        }


查看完整回答
反对 回复 2019-07-08
  • 3 回答
  • 0 关注
  • 399 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信