【问题标题】:Making a checkerboard pattern using CSS Selectors使用 CSS 选择器制作棋盘图案
【发布时间】:2022-01-06 18:01:53
【问题描述】:

我有一个 div 元素列表,我目前使用 CSS 浮动在两列中显示这些元素。我想“交替”这些元素的边框颜色。我在引号中使用了备用,因为我真正想要的是每个“行”中的两个 div 交替。下面是我想要的最终状态的示例:

1blue   2green
3green  4blue
5blue   6green
7green  8blue

如果我简单地使用 nth-child(even) 或 nth-child(odd) 我会在垂直的每一列中得到相同的颜色,例如:

1blue 2green
3blue 4green
5blue 6green
7blue 8green

我要定位的 div 位于 WordPress 循环内,因此我对标记没有太多控制权(这就是我希望使用 CSS nth-child 的原因)。不幸的是,没有任何标记可以让我定位每个单独的“行”。

是否有任何类型的 nth-child 模式可以让我对无限数量的项目执行类似blue[1], green[2],blue[2],etc 的操作?

我通常对 CSS 有很好的理解,但这有点伤脑筋,所以提前感谢您的帮助!

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    看起来你正在制作一个简单的棋盘格,所以如果你将所有东西都设置为绿色,你只需要覆盖所有需要为蓝色的东西。 nth-child can also accept a fomula that gives an n or multiple of n with an offset.

    当您为它们编号时,请注意在右列中您有 48(下一个是 12),因此您需要每个第 4 个元素,在左列中您有 15(下一个是9),所以你还需要第四个加一(从技术上讲,1 是4*0+1)。

    There is a fiddle here that demos it,但是相关代码是:

    /* Color everything green */
    .checkerboard div {
        width:45%;
        display:inline-block;
        background-color:green;
    }
    
    /* Then color the appropriate divs blue */
    .checkerboard div:nth-child(4n+1),
    .checkerboard div:nth-child(4n) {
        background-color:blue;
    }
    

    并给出:

    【讨论】:

    • 这正是我所需要的。谢谢!
    【解决方案2】:

    你可以只制作蓝色 1 和绿色 2:

    1:nth-of-type(2n+1){
       background-color: green;
    }
    
    2:nth-of-type(2n){
       background-color: blue;
    }
    

    并确保将 id 设置为 1 和 2 以使其正常工作

    【讨论】:

      【解决方案3】:

      你应该像这样使用nth-child

      div:nth-child(1){…your code here…}
      div:nth-child(2){…your code here…}
      div:nth-child(3){…your code here…}
      div:nth-child(4){…your code here…}
      div:nth-child(5){…your code here…}
      div:nth-child(6){…your code here…}
      div:nth-child(7){…your code here…}
      div:nth-child(8){…your code here…}
      

      通过这个你可以对你的 8 个 div 元素中的每一个做任何事情。

      【讨论】:

      • 如果有第 9 个元素、第 10 个或第 100 个元素会怎样?
      • 你应该像这样“div:nth-child(100)”把括号里的数字传递给nth-child。
      • 所以如果我有 12 个,我需要...div:nth-child(9){}div:nth-child(10)div:nth-child(11)div:nth-child(12)?
      • 那个乐高风暴的家伙是一个 froody 程序员。
      • @LegoStormtroopr ahem,我相信正确的形容词形式是“hoopy”。比如,“赞福德就是这个人,你知道吗?他是个疯子。”
      猜你喜欢
      • 1970-01-01
      • 2016-05-23
      • 2022-11-04
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 2021-07-07
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多