【问题标题】:CSS3 Nth Child orderingCSS3 Nth Child 排序
【发布时间】:2015-03-16 00:22:03
【问题描述】:

我希望使用 nth-child 来定位元素,有 3 种颜色(grey-1、grey-2 和 gray-3)。

在第四个元素上,我希望颜色循环例如

  • 灰1
  • 灰2
  • 灰3
  • 灰1
  • 灰2
  • 灰3

什么是最有效的方法,我可以选择使用 jQuery,但更喜欢使用 CSS3。列表可能很长,这就是为什么我不想用 .addClass() 更改 dom。

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    MDN - nth-child

    :nth-child(an+b) CSS 伪类匹配文档树中在它之前具有an+b-1 兄弟姐妹的元素,对于n 的给定正值或零值,并且具有父元素。更简单地说,选择器匹配多个子元素,这些子元素在一系列子元素中的数字位置与模式an+b 匹配。

    为了选择每三个元素,您可以使用:nth-child(3n)。相应地增加 b 以定位所有元素 :nth-child(3n+1):nth-child(3n+2):nth-child(3n+3)

    Example Here

    div:nth-child(3n+1) {
        background: #ccc;
    }
    div:nth-child(3n+2) {
        background: #ddd;
    }
    div:nth-child(3n+3) {
        background: #eee;
    }
    

    div {
        height: 20px;
    }
    div:nth-child(3n+1) {
        background: #ccc;
    }
    div:nth-child(3n+2) {
        background: #ddd;
    }
    div:nth-child(3n+3) {
        background: #eee;
    }
    <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>

    【讨论】:

      【解决方案2】:

      假设元素是公共容器的直接子元素(例如liul 的子元素),您可以这样做

      li:nth-child(3n+1) {
        color: green
      }
      li:nth-child(3n+2) {
        color: blue
      }
      li:nth-child(3n+3) {
        color: red
      }
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
        <li>7</li>
      </ul>

      【讨论】:

        猜你喜欢
        • 2012-05-10
        • 1970-01-01
        • 2012-04-20
        • 1970-01-01
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-01
        相关资源
        最近更新 更多