【发布时间】: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