Style every third element?(每隔三个元素设置样式?)
问题描述
如何使用纯 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 及以下版本.
这篇关于每隔三个元素设置样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每隔三个元素设置样式?


基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01