nth-child不响应类选择器 [英] nth-child doesn't respond to class selector

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

问题描述

除非它不应该,但我似乎不能得到 nth-child 承认类选择器。

Unless it's not supposed to but I can't seem to get nth-child to acknowledge the class selector.

我已经说了4个div在另一个div,所有的各种类和ids。我需要选择与所述类的div的第一个实例。例如:

I have say 4 divs inside another div, all of various classes and ids. I need to select the first instance of a div with said class. For example:

#content .foo:nth-child(1) { margin-top: 0; }

显然再次使用 first-child 以获得相同的效果,但它不会影响任何div。

And obviously again with first-child to get the same affect, but it doesn't affect any of the divs.

现在,如果我想强制它使用div,我可以这样做: / p>

Now if I want to force it to work with that div I can do this:

#content .foo:nth-child(3) { margin-top: 0; }

它只是这样发生,它是#content的第三个div,这是无意义,以获得该类的任何内容的第一个实例。

It just so happens that it is the 3rd div in #content, which is pointless because I need to get the 1st instance of anything with that class.

<div id="content">  
  <div id="action-bar"> </div>
  <div id="message"> </div>
  <div class="table"> </div>
  <div class="clear"> </div>
</div>

下面是一个HTML示例,我试过 nth-of-类型也是这样:

Here's a sample of the HTML, I've tried nth-of-type as well like this:

#content .table:nth-of-type(1) { margin: 0 }

同样,只有当我说 nth-of -type(3)

我遇到的问题的工作示例: http://jsfiddle.net/aHwS8/

I've set up a working example of the problem I'm having here: http://jsfiddle.net/aHwS8/

推荐答案

尝试

Try the :nth-of-type() pseudo-selector instead:

#content .foo:nth-of-type(1) { margin-top: 0; }

注意:nth-​​of-type()计数具有相同名称的元素。所以 .foo:nth-​​of-type(1)不会选择类 foo 的第一个元素,在以相同名称分组的元素列表中。如果您有这样的文档:

Note that :nth-of-type() counts the elements with the same name. So .foo:nth-of-type(1) will not select the first element with the class foo but any first element that is the first in the list of elements grouped by the same name. If you have some document like this:

<div>
    <i class="foo">1</i><i>x</i><i class="foo">2</i>
    <b class="foo">3</b><b>x</b><b class="foo">4</b>
</div>

.foo:nth-​​of-type(1)将选择元素< i class =foo> 1< / i> < b class =foo > 3< / b> ,因为两者都是自己类型的第一个。

.foo:nth-of-type(1) will select the elements <i class="foo">1</i> and <b class="foo">3</b> as both are the first of its own type.

这篇关于nth-child不响应类选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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