問題描述
如何使用純 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 及以下版本.
這篇關于每隔三個元素設置樣式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!