本文介绍了使用CSS选择器创建棋盘图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果我只是使用nth-child (odd)我在每一列垂直像相同的颜色:

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

我想要定位的div位于WordPress循环中我没有很多控制的标记(这就是为什么我希望使用CSS的第n个孩子)。不幸的是,没有任何标记可以让我针对每个单独的行。



有任何一种nth-child模式,对于不定数量的项目,如 blue [1],green [2],blue [2]等等


解决方案
我通常对CSS有很好的理解,但这是伤害我的大脑, p>看起来你正在做一个简单的棋盘,所以如果你把每一个东西设置为绿色,你只需要重写一切需要是蓝色的。 的 n 的倍数的公式。



请注意,在右栏中您有 4 8 (下一个是 12 ),因此您需要每个第4个元素,而在左侧有 1 5 (接下来会是 9 ),因此您还需要第四加一(技术上 4 * 0 + 1 )。



,但相关代码是:

  / *颜色一切绿色* / 
.checkerboard div {
width:45%;
display:inline-block;
background-color:green;
}

/ *然后颜色适当的divs蓝色* /
.checkerboard div:nth-​​child(4n + 1),
.checkerboard div: child(4n){
background-color:blue;
}

并提供:




I have a list of div elements that I'm currently displaying in two columns using CSS float. I would like to "alternate" the border color of these elements. I used alternate in quotes because what I really want is for the two divs in each "row" to alternate. Below is an example of what I want as my end state:

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

If I simply use nth-child(even) or nth-child(odd) I get the same color in each column vertically like:

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

The divs I want to target are located inside a WordPress loop so I don't have a lot of control over the markup (which is why I was hoping to use CSS nth-child). Unfortunately there isn't any markup that would allow me to target each individual "row".

Is there any kind of nth-child pattern that would allow me to do something like blue[1], green[2],blue[2],etc for an indefinite number of items?

I normally have a very good understanding of CSS but this is hurting my brain a little so thanks in advance for any help!

解决方案

It seems like you are making a simple checkerboard, so if you set every thing to green, you just need to override everything that needs to be blue. nth-child can also accept a fomula that gives an n or multiple of n with an offset.

As you have them numbered, note that in the right column you have 4 and 8 (next would be 12), so you need every 4th element, and in the left you have 1 and 5 (next would be 9), so you also need the 4th plus one (1 is technically 4*0+1).

There is a fiddle here that demos it, but the relevant code is:

/* 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;
}

And gives:

这篇关于使用CSS选择器创建棋盘图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:23