【问题标题】:nth-child calculating incorrectlynth-child 计算错误
【发布时间】:2014-09-23 15:49:00
【问题描述】:

我有一组 div,我希望每三个 div 在右侧没有边距。自然,我认为 div:nth-child(3n) 会起作用。它不是。我做了一些研究,它似乎在计算要影响的元素时计算父 div 中的所有元素。结果是它的目标不是每三个 div,而是每三个恰好是 div 的元素。详细来说,看看这个http://jsfiddle.net/3wV9p/3/

<style type="text/css>
    div:nth-child {
        background-color: blue;
        color: white;
    }
</style>
<h1>Hello World</h1>
<p>A paragrapgh tag.</p>
<p>A second paragrapgh tag</p>
<p>I want these to be ignored.</p>
<p>I just want every third div (3, 6, 9, 12) to be blue.</p>
<div>The 1st div.</div>
<div>The 2nd div.</div>
<div>The 3rd div.</div>
<div>The 4th div.</div>
<div>The 5th div.</div>
<div>The 6th div.</div>
<div>The 7th div.</div>
<div>The 8th div.</div>
<div>The 9th div.</div>
<div>The 10th div.</div>
<div>The 11th div.</div>
<div>The 12th div.</div>

假设我希望每三个 div 都是蓝色的,我该如何弥补它计算 p 和 h1 标签的事实?我意识到我可以通过其他元素的数量(在这种情况下为 5)来抵消,但在我需要使用它的上下文中,前面的元素是动态生成的,因此不可能知道偏移量需要是多少。

总而言之,我需要一种方法来计算我关心的元素,而不是同一级别的每个元素。这甚至可以用 CSS 实现还是我需要实现一些 JS/jQuery?真正令人沮丧的部分是我在 nth-child() 上找到的任何文档都没有接近表明它以这种方式运行。我必须通过反复试验自己弄清楚。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    补偿不相关元素的唯一方法是使用不同的选择器。 :nth-child() 选择器在这里按预期工作,因为您的 p 和 h1 元素都是您的 div 元素的兄弟,共享同一个父元素(即 body 元素)。

    在这种情况下,由于它们之间的唯一区别是元素类型,you can use :nth-of-type() instead

    div:nth-of-type(3n) {
        background-color: blue;
        color: white;
    }
    

    在更复杂的情况下,例如当您的 div 元素具有不同的类名、属性等时,您将无法使用纯 CSS 仅计算您想要的元素。这是因为没有:nth-of-class() 或其他类似的选择器,或者只计算匹配某个任意条件/选择器的元素的方法。请参阅我对this question 的回答以获得更详细的说明。

    jQuery 用:eq() selector 在某种程度上弥补了这个限制,但它的工作方式与:nth-child():nth-of-type() 非常不同,并且可能并不总是提供足够的替代品。没有与 jQuery 的 :eq() 等效的 CSS。有关差异的说明,请参阅 this answer

    【讨论】:

      【解决方案2】:

      您可以使用nth-of-type 选项。 nth-of-type 选择与n 匹配的那个类型的元素。因此,在下面的示例中,它将选择每第三个 div 元素。

      div:nth-of-type(3n){
          background-color: blue;
          color: white;
      }
      

      Demo

      【讨论】:

        猜你喜欢
        • 2013-12-27
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        相关资源
        最近更新 更多