每4项备用颜色

时间:2019-04-30 02:14:55

标签: html css css-selectors

使用纯CSS是否可以创建每隔4个项目交替出现的颜色网格。例如;前4个项目为蓝色,接下来的4个项目为红色,然后下4个项目为蓝色,依此类推。

<div>Item 1 = blue</div>
<div>Item 2 = blue</div>
<div>Item 3 = blue</div>
<div>Item 4 = blue</div>
<div>Item 5 = red</div>
<div>Item 6 = red</div>
<div>Item 7 = red</div>
<div>Item 8 = red</div>
<div>Item 9 = blue</div>

有什么想法吗?我知道有nth-child(odd)even,但不确定这里是否有帮助...

3 个答案:

答案 0 :(得分:5)

可以使用红色的默认规则,而对于蓝色重复使用偏移的规则。

8n+1每8个偏移量为1的语法,然后重复此操作以得到1到4。

div {
  color: red;
}

div:nth-child(8n+1),
div:nth-child(8n+2),
div:nth-child(8n+3),
div:nth-child(8n+4) {
  color: blue;
}
<div>Item 1 = blue</div>
<div>Item 2 = blue</div>
<div>Item 3 = blue</div>
<div>Item 4 = blue</div>
<div>Item 5 = red</div>
<div>Item 6 = red</div>
<div>Item 7 = red</div>
<div>Item 8 = red</div>
<div>Item 9 = blue</div>

答案 1 :(得分:4)

您可以使用一些详细的 nth-child 逻辑-请参见下面的演示

THREE.VrayPost = {
uniforms: {
    "map": { value: null },     
    "exposure": { value: null },        
    "brightmax": { value: null },               
},
vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
        "vUv = uv;",
        "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
].join( "\n" ),
fragmentShader: [
    "uniform sampler2D map;",

    'uniform sampler2D   tDiffuse;',
    'uniform float       exposure;',
    'uniform float       brightMax;',

    "varying vec2 vUv;",

    'vec3 decode_pnghdr( const in vec4 color ) {',
    '   vec4 rgbcolor = vec4( 0.0, 0.0, 0.0, 0.0 );',
    '   if ( color.w > 0.0 ) {',
    '       float f = pow(2.0, 127.0*(color.w-0.5));',
    '       rgbcolor.xyz = color.xyz * f;',
    '   }',
    '   return rgbcolor.xyz;',
    '}',

    "void main() {",
        'vec4 color = texture2D( map, vUv );',
        'color.xyz  = decode_pnghdr( color );',

        "gl_FragColor = vec4( color.xyz, 1.0 )*vec4(exposure);",
    "}"
].join( "\n" )
div:nth-child(4n),
div:nth-child(4n - 1),
div:nth-child(4n - 2),
div:nth-child(4n - 3) {
  color: blue;
}

div:nth-child(8n),
div:nth-child(8n - 1),
div:nth-child(8n - 2),
div:nth-child(8n - 3) {
  color: red;
}

/* stylings */
body {
  counter-reset: counter;
}

div {
  counter-increment: counter;
}

div:after {
  content: counter(counter);
}

答案 2 :(得分:-2)

我认为这就是您想要的。

让我知道是否可以

div:nth-child(2n) {
  color:blue;
}
div:nth-child(3n) {
  color:green;
}
div:nth-child(4n) {
  color:red;
}
<div>
  <div>Item 1 = blue</div>
  <div>Item 2 = blue</div>
  <div>Item 3 = blue</div>
  <div>Item 4 = blue</div>
  <div>Item 5 = red</div>
  <div>Item 6 = red</div>
  <div>Item 7 = red</div>
  <div>Item 8 = red</div>
  <div>Item 9 = blue</div>
</div>