【问题标题】:How can I style only certain columns in a div? [duplicate]如何仅对 div 中的某些列进行样式设置? [复制]
【发布时间】:2015-08-01 19:25:19
【问题描述】:

我在一个整体容器中有一系列 div:

<div class="positionDivs">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <!--this goes on for a unspecified number of times-->
</div>

这在主 div (positionDivs) 内显示为三列

我需要做的是在这个容器中每隔三个 div 设置样式:

.positionDivs div:nth-child(3n){
    background-color:black;
} 

但我也(这是我无法解决的部分!)需要设置中心栏的样式。在上面的示例中,这将是数字 2、5 和 8。

有人可以帮忙吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    只需从你必须选择的前一个 div 中减去一个:

    .positionDivs div:nth-child(3n-1){
        background-color:red;
    } 
    

    jsFiddle example

    【讨论】:

    • 你我的朋友是个天才!
    • @SxChoc 或者他之前只看过这个问题五十次 :-)
    【解决方案2】:

    nth-child 中使用3n+2

    .positionDivs div:nth-child(3n+2){
        background-color:red;
    }
    

    3n-1,两者都返回相同的结果。

    .positionDivs div:nth-child(3n-1){
        background-color:red;
    }
    

    【讨论】:

      【解决方案3】:

      使用3n+2

      .positionDivs div:nth-child(3n+2){
         /* CSS Properties */
       } 
      

      3n-1

      .positionDivs div:nth-child(3n-1){
         /* CSS Properties */
       } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-30
        • 2019-05-21
        • 2019-11-07
        • 2015-05-02
        • 2010-12-02
        • 2016-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多