如何使用纯 CSS 设置每三个元素的样式。
我见过这样的问题,但是涉及到javascript。我想要一个简单的 CSS 解决方案。我知道我可以将 even
或 odd
与 :nth-child
一起使用,但 :nth-child(third)
不会: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?
最佳答案
这可以通过纯 CSS 实现。不需要 javascript。
使用 nth-child selector .1
section > div:nth-child(3n+1) {
background:red;
}
其中“1”是样式开始的位置,3 表示它应该每隔三个元素设置样式。解释得更好here .
1注意 - 正如其他人提到的那样,这是 not fully supported IE8 及以下版本。
关于html - 每三个元素设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860786/