每隔三个元素设置样式?
如何使用纯 CSS 设置每三个元素的样式.
How can I style every third element with plain CSS.
我见过这样的问题,但它们涉及到 javascript.我想要一个简单的 CSS 解决方案.我知道我可以将 even
或 odd
与 :nth-child
一起使用,但 :nth-child(third)
不能:nth-child(3)
I have seen questions like this, but they involve javascript. I want a plain CSS solution. I know I can use even
or odd
with :nth-child
but :nth-child(third)
doesn't work neither does :nth-child(3)
例子:
<section>
<div class="someclass"></div> STYLE
<div id="someId"></div> DON'T STYLE
<div class="someotherclass"></div> DON'T STYLE
<div id="someotherId"></div> STYLE
<div class="someclass"></div> DON'T STYLE
<div id="someId"></div> DON'T STYLE
<div class="someotherclass"></div> STYLE
</section>
这可以通过 CSS 实现吗?没有 javascript 或 jQuery?
Is this possible with CSS - no javascript or jQuery?
推荐答案
纯 CSS 可以做到这一点.无需 javascript.
This is possible with pure CSS. No javascript needed.
使用 nth-child 选择器.1
section > div:nth-child(3n+1) {
background:red;
}
其中1"是样式的开始位置,3 表示应该每隔三个元素设置样式.这里解释得更好.
Where '1' is where the style starts, and 3 indicates that it should style every third element. It is explained much better here.
jsFiddle 演示在这里.
1注意 - 正如其他人所提到的,这是 不完全支持 IE8 及以下版本.
相关文章