在没有 jquery 的情况下,每第 4 个 odd/even nth-child(2n) 设置样式

Style every 4th alternative odd/even nth-child(2n) without jquery

当前情况

我想要什么

请参阅以下代码段进行编辑。希望对您有所帮助。

ul {
    font-size: 0;
    width: 400px;
}
li {
    width: 100px;
    height: 100px;
    display: inline-block;
}
li:nth-child(odd) {
    background: yellow;
}
li:nth-child(even) {
    background: orange;
}
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
</ul>

如果可能,我需要纯 CSS 解决方案。

本质上,您使用的是偏移量为 8 的重复组,因此您可以使用:

ul {
    font-size: 0;
    width: 400px;
}
li {
    width: 100px;
    height: 100px;
    display: inline-block;
    background: yellow;
}
li:nth-child(8n+2), li:nth-child(8n+4), li:nth-child(8n+5), li:nth-child(8n+7) {
    background: orange;
}
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
    <li>12</li>
</ul>

啊,刚刚做了这个,看到了基本相同的答案——我用了 8n 并减去。

ul {
  width: 400px;
  padding: 0;
  margin: 0;
  position: relative;
  display: inline-block;
}
li {
  width: 100px;
  height: 55px;
  padding: 0;
  margin: 0;
  background-color: #FF8E00;
  list-style-type: none;
  text-align: center;
  display: inline-block;
  padding-top: 45px;
  font-family: Arial;
  font-size: 18px;
  font-weight: bold;
  color: #777;
}
li:nth-child(odd),
li:nth-child(8n),
li:nth-child(8n - 2) {
  background-color: #ff0;
}
li:nth-child(8n - 3),
li:nth-child(8n - 1) {
  background-color: #FF8E00;
}
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>