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

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

问题描述

除非不应该这样做,但我似乎无法让 nth-child 确认类选择器.

我说另一个 div 中有 4 个 div,所有不同的类和 id.我需要选择具有所述类的 div 的第一个实例.例如:

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

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

现在,如果我想强制它与该 div 一起工作,我可以这样做:

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

碰巧它是#content 中的第三个 div,这是没有意义的,因为我需要使用该类获取任何东西的第一个实例.

<div id=内容"><div id="操作栏"></div><div id=消息"></div><div 类=表"></div><div 类=清除"></div></div>

这是一个 HTML 示例,我也尝试过 nth-of-type,如下所示:

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

同样,它只在我说 nth-of-type(3) 时才会响应.

我在这里设置了一个工作示例:http://jsfiddle.net/aHwS8/

解决方案

试试 :nth-of-type() 伪选择器 代替:

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

请注意,:nth-of-type() 会计算具有相同名称的元素.所以 .foo:nth-of-type(1) 不会选择第一个具有类 foo 的元素,而是选择分组元素列表中第一个的任何第一个元素同名.如果你有这样的文件:

<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> 因为两者都是它自己的类型中的第一个.

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

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

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

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

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

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>

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 }

Again it only responds when I say nth-of-type(3).

EDIT:

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

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) 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天全站免登陆