【问题标题】:Grouped sequence with CSS :nth-child使用 CSS 分组序列:nth-​​child
【发布时间】:2020-12-13 04:46:48
【问题描述】:

ul,li {
  display: block;
  margin:0;
  padding:0;
  list-style:none;
}
li {
  background: black;
  color: white;
  padding: 10px;
}
li:nth-child(2n+2) {
  background: red;
}
li:nth-child(3n+3) {
  background: green;
}
li:nth-child(4n+4) {
  background: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
  <li>nine</li>
  <li>ten</li>
  <li>eleven</li>
  <li>twelve</li>
</ul>

我需要什么

  1. 黑色
  2. 红色
  3. 绿色
  4. 蓝色
  5. 黑色
  6. 红色
  7. 绿色
  8. 蓝色
  9. ...

...如何使用:nth-child 实现这一目标?

【问题讨论】:

    标签: html css css-selectors html-lists pseudo-class


    【解决方案1】:

    给定nth-child 语法

    :nth-child( <an-plus-b>  )
    

    您需要使用4n+b 进行迭代

    所以,

    对于背景 red 它将是 4n+2 所以,4x0+24x1+24x2+2 等等,它给你元素 2、6、10

    对于背景 green 它将是 4n+3 所以,4x0+34x1+34x2+3 等等,它给你元素 3、7、11

    对于 background'blue,它将是 4n+4 所以,4x0+44x1+44x2+4 等等,这会给你元素 4、8、12

    根据您在li 中的属性,其余元素1、5、9 将默认为black 着色

    ul,li {
      display: block;
      margin:0;
      padding:0;
      list-style:none;
    }
    li {
      background: black;
      color: white;
      padding: 10px;
    }
    li:nth-child(4n+2) {
      background: red;
    }
    li:nth-child(4n+3) {
      background: green;
    }
    li:nth-child(4n+4) {
      background: blue;
    }
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
      <li>four</li>
      <li>five</li>
      <li>six</li>
      <li>seven</li>
      <li>eight</li>
      <li>nine</li>
      <li>ten</li>
      <li>eleven</li>
      <li>twelve</li>
    </ul>

    【讨论】:

    • AFAIK [ of &lt;selector&gt;# ]? 语法尚不支持。
    • @Oriol tbh 我从MDN 获得了语法,但是在选择器级别 4 link 中似乎是 WD@
    • 感谢您的解释!
    • 欢迎您! @Oriol 我更新了答案,不包括选择器级别 4 的语法,
    【解决方案2】:

    您可以使用 nth-child 进行如下操作

    由于索引 1,5 和 9 需要黑色,因此可以处理 4n+1 索引 2,6,10 为红色,可以处理 4n+2

    检查这个sn-p

    ul,
    li {
      display: block;
      margin: 0;
      padding: 0;
      list-style: none;
    }
    li {
      background: black;
      color: white;
      padding: 10px;
    }
    li:nth-child(4n+1) {
      background: black;
    }
    li:nth-child(4n+2) {
      background: red;
    }
    li:nth-child(4n+3) {
      background: green;
    }
    li:nth-child(4n+4) {
      background: blue;
    }
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
      <li>four</li>
      <li>five</li>
      <li>six</li>
      <li>seven</li>
      <li>eight</li>
      <li>nine</li>
      <li>ten</li>
      <li>eleven</li>
      <li>twelve</li>
    </ul>

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-07-30
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2016-09-19
      • 2012-03-14
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多