nth-of-type vs nth-child [英] nth-of-type vs nth-child

查看:131
本文介绍了nth-of-type vs nth-child的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对nth-of-type伪类有些困惑,特别是与第n个子类相比,这是如何工作的。

I am a bit confused about the nth-of-type pseudo class, and how this is supposed to work - especially as compared to the nth-child class.

可能我有错误的想法,但给定此结构

Maybe I have the wrong idea, but given this structure

<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>

..第三个子元素(第一个带类标签) / p>

..the third child element (first with class label) should (perhaps?) be selectable with

.row .label:nth-of-type(1) {
    /* some rules */
}

但是,至少在chrome中,它不会选择它。它只是看起来工作,如果它是行中的第一个孩子,这是相同的nth-child - 因此,这和类型之间的区别是什么?

However, at least in chrome here, it doesn't select it. It only appears to work if it is the first child in the row, which is the same as nth-child - therefore, what is the difference between this and nth-of-type?

推荐答案

nth-child 伪类指的是第N个匹配的子元素,意味着如果您有一个结构如下:

The nth-child pseudo-class refers to the "Nth matched child element", meaning if you have a structure as follows:

<div>
    <h1>Hello</h1>

    <p>Paragraph</p>

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

然后 p:nth-​​child(2)将选择也是ap的第二个子级(即 p 和段落)。

p:nth -of-type 将选择第二个匹配 p 元素(即我们的目标 p )。

Then p:nth-child(2) will select the second child which is also a p (namely, the p with "Paragraph").
p:nth-of-type will select the second matched p element, (namely, our Target p).

这是Chris Coyier @ CSS-Tricks.com关于此主题的精彩文章

Here's a great article on the subject by Chris Coyier @ CSS-Tricks.com

你的断裂的原因是因为类型指的是元素的类型(即 div ),不符合您提到的规则( .row .label ),因此规则不适用。

The reason yours breaks is because type refers to the type of element (namely, div), but the first div doesn't match the rules you mentioned (.row .label), therefore the rule doesn't apply.

原因是, CSS从右向右解析 ,这意味着浏览器首先查看:nth-​​of-type(1),确定它搜索类型 div的元素 .row 元素,第一个 .icon / code>元素。然后它读取元素应该有 .label 类,它不匹配上面的任何东西。

The reason is, CSS is parsed right to left, which means the the browser first looks on the :nth-of-type(1), determines it searches for an element of type div, which is also the first of its type, that matches the .row element, and the first, .icon element. Then it reads that the element should have the .label class, which matches nothing of the above.

如果你想要选择第一个标签元素,您需要将所有标签包装在自己的容器中,或者直接使用 nth-of-type(3)

If you want to select the first label element, you'll either need to wrap all of the labels in their own container, or simply use nth-of-type(3) (assuming there will always be 2 icons).

另一个选项,会(可悲的是)使用...等待... jQuery:

Another option, would (sadly) be to use... wait for it... jQuery:

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

这篇关于nth-of-type vs nth-child的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆