html - 每八个 (8) 第 n 个 child

标签 html css css-selectors

我需要像这样使用第 nth-child 每八个元素重复一个模式。

■□■□

□■□■

我一直在试图找出一个公式,但我似乎没有弄对。

section {
  width: 220px;
}
div {
  width: 50px;
  height: 50px;
  float: left;
  margin-right: 5px;
  margin-bottom: 5px;
  background-color: yellow;
}

div:nth-child(4n), div:nth-child(4n+1) {
  background-color: green;
}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>

最佳答案

如果您必须保留 <br>元素,那么你不想使用 nth-child作为 <br>会算作 child 。相反,您可以使用 nth-of-type :

div:nth-of-type(5n+1),div:nth-of-type(5n+3) {
  background-color: green;
}

例子:

div {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-color: yellow;
}

div:nth-of-type(5n+1),div:nth-of-type(5n+3) {
  background-color: green;
}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <br>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>

根据您问题中的更新信息,看起来更好的解决方案是 div:nth-of-type(8n+1), div:nth-of-type(8n+3),div:nth-of-type(8n+6), div:nth-of-type(8n+8) { background-color: green; }

body {
  font-size: 10pt;
}

section {
  width: 220px;
}

div {
  width: 50px;
  height: 50px;
  float: left;
  margin-right: 5px;
  margin-bottom: 5px;
  background-color: yellow;
}

div:nth-of-type(8n+1),
div:nth-of-type(8n+3),
div:nth-of-type(8n+6),
div:nth-of-type(8n+8) {
  background-color: green;
}
<section>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div>Should repeat here</div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div>Should repeat here</div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</section>

关于html - 每八个 (8) 第 n 个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45037879/

相关文章:

javascript - servlet 处理时显示模式框

javascript - Html5 输入属性的默认值,如 min 、 max 、 size 等

html - 尝试向导航栏添加新元素并向网站添加新页面[找不到错误]

css - 为什么这个选择器在 Chrome 的这个页面上返回两个元素?

javascript - 如何使用:not selector in Cytoscape. js? (选择没有属性的节点)

html - Safari 不计算高度 : 100% on nested flexbox

html - 如何使一个div与其他div重叠?

html - css 淡出边缘的框阴影

css - 在创建的 :, 中,我的方法无法正常工作

css - 如何将文本阴影添加到 Twitter Bootstrap 导航栏链接?