CSS不顺利

时间:2013-12-25 20:07:34

标签: javascript jquery css html

第n的型

我想通过nth-of-type称它们为“第一,第二,第三”来获得div 现在的问题是这有效:

.box:nth-of-type(1)
.box:nth-of-type(3)
.box:nth-of-type(5)

但我不明白为什么我不能这样称呼他们:

.box:nth-of-type(1)
.box:nth-of-type(2)
.box:nth-of-type(3)

就是这样:

<div class="box"></div>
<div class="divider"></div>
<div class="box"></div>
<div class="divider"></div>
<div class="box"></div>

当我移除它们之间的两个分隔符时,问题就解决了(有两个div称为“分频器”)所以我可以称它们为1,2,3,但为什么我需要将它们称为1,3 ,5用分隔线?此外,当我将div更改为p或h1等其他任何东西时......好吧我可以称它们为1,2,3

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

:nth-of-type与具有相同标记名称的兄弟元素相关。它没有类的概念。

所以只有在以下情况下才会满足.box:nth-of-type(X)选择器:

  • 该元素包含box
  • 它相对于具有相同标记名称的兄弟姐妹的位置符合nth-of-type规则。

解决方案:将您的box或divider元素切换到另一个标记,它将按预期工作。

Demo

<div class="box"></div>
<p class="divider"></p>
<div class="box"></div>
<p class="divider"></p>
<div class="box"></div>

.divider { margin:0; }
.box:nth-of-type(1) {
  /* custom styling for the .box which is
   * the first element among its siblings which have the same tag name (div)
   */
}
.box:nth-of-type(2) { /* same now for the 2nd */ }
.box:nth-of-type(3) {}

您可能还希望将选择器更改为div.box:nth-of-type(X),以便更清楚地表明nth-of-type关系与div元素相关。

注意:当然,在div es之前添加另一个.box会破坏这些nth-of-type规则。因此,使用此选择器时必须小心,因为更改DOM结构可能会影响样式。

通常使用的坚固替代方案(对于像我这样对DOM结构的未来变化的偏执)是应用修饰符类(在BEM methodology之后):

<div class="box box--1"></div>

.box { /*base style for all boxes here*/ }
.box--1 { /* custom styles for the box--1 */ }

答案 1 :(得分:1)

nth-of-type适用于类型而不是类。因此,当您将它与类一起使用时,它将找到类的类型并使用它来查找元素。

与你的情况类似,它会评估.box的类型为div,然后如果你使用divider则会找到1,2和3或1,3和5。

答案 2 :(得分:0)

Nth-of-type仅根据元素类型进行选择。你不能选择类,所以它只是看着div。

来自quirksmode:

  

:nth-​​of-type()的工作方式相同,只是它只考虑给定类型的元素(在示例中)。

http://quirksmode.org/css/selectors/nthchild.html

既然你已经给了想要选择一个类的那个,为什么不使用.box作为没有伪类的选择器呢?