【问题标题】:CSS Not going well [duplicate]CSS进展不顺利[重复]
【发布时间】:2014-01-13 14:36:38
【问题描述】:

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

当我删除它们之间的两个分隔符时问题得到解决(有 2 个称为“分隔符”的 div),所以我可以将它们称为 1、2、3,但为什么我需要称它们为 1、3 , 5 用分频器?此外,当我将 div 更改为 p 或 h1 等其他任何内容时...没关系,我可以称它们为 1、2、3

感谢您的帮助!

【问题讨论】:

  • 你会想要:nth-match()(当它被实现时),而不是:nth-of-type()。

标签: javascript jquery css html


【解决方案1】:

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

来自怪癖模式:

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

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

既然你已经给出了你想要选择的类,为什么不直接使用 .box 作为你的选择器而不使用伪类呢?

【讨论】:

  • 谢谢,我明白为什么它不好。关于这个问题,我已经为所有 3 个 div 使用了全局样式的 .box 选择器,但是因为每个框都有不同的样式,所以我需要单独选择它们。
【解决方案2】:

:nth-of-type 相对于具有相同标签名称的兄弟元素。它没有类的概念。

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

  • 元素具有box 类和
  • 其相对于具有相同标签名称的兄弟的位置满足nth-of-type 规则。

解决方案:将您的框或分隔元素切换到另一个标签,它会按您的预期工作。

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 元素的关系。

注意:当然,在.boxes 之前添加另一个div 会破坏这些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 */ }

【讨论】:

  • 感谢您的深入解释!现在好了
【解决方案3】:

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

就像你的情况一样,它会将 .box 的类型评估为 div,然后如果你使用分隔符,则找到 1、2 和 3 或 1、3 和 5。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多