Home > Net >  Changing background colors in a specific sequence with CSS
Changing background colors in a specific sequence with CSS

Time:05-16

I am building out a masonry grid which is 3 columns. I need for each grid item to have a background color applied to it via CSS, but in a specific order:

  • Blue, green pink
  • Green, pink, blue
  • Pink, blue, green
  • (repeat)

I have tried the following, but it doesn't quite get me there:

.masonry_item:nth-child(3n 1) {
  background: blue;
}
.masonry_item:nth-child(3n 2) {
  background: green;
}
.masonry_item:nth-child(3n 3) {
  background: pink;
}

Here is a simplified version of the HTML:

<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>

CodePudding user response:

Maybe you can try this way?? By adding a new class you can just designate their color.

.masonry_container {
  display: grid;
  grid-template-columns: auto auto auto;
  grid-gap: 20px;
  }
  
.masonry_item {
  width: 100px;
  height:100px;
  border: 1px solid black;

  }

.blue {background-color: blue;}
.green {background-color: green;}
.pink {background-color: pink;}
<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>

CodePudding user response:

You can try using :even and :odd pseudo-classes

  • Related