Home > Software design >  Using nth of child in CSS to create an uneven pattern?
Using nth of child in CSS to create an uneven pattern?

Time:08-17

There is a grid of 9 elements, their colors are like this:

Blue, Gray, Green
Green, Blue, Gray
Gray, Green, Blue

and then it repeats Blue, Gray, Green - how can I use nth of child to create this kind of pattern?

CodePudding user response:

This is the rough and dirty way to accomplish this, using vanilla CSS and :nth:child formulas. With :nth-child, you are essentially writing a math expression to determine the behavior of elements that meet xn y. Since you know your starting size, it's fairly simple to declare each one:

.child:nth-child(9n 1){
    background: blue;
}

But you can view my snippet for a full demo.

.parent{ 
  display: grid;
  grid-template-columns: max-content max-content max-content;
  gap: 10px;
}

.child{
  width: 100px;
  height: 100px;
}

.child:nth-child(9n 1){
  background: blue;
}
.child:nth-child(9n 2){
  background: gray;
}
.child:nth-child(9n 3){
  background: green;
}
.child:nth-child(9n 4){
  background: green;
}
.child:nth-child(9n 5){
  background: blue;
}
.child:nth-child(9n 6){
  background: gray;
}
.child:nth-child(9n 7){
  background: gray;
}
.child:nth-child(9n 8){
  background: green;
}
.child:nth-child(9n 9){
  background: blue;
}
<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 ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

Edit: Here is a less redundant version, using shared properties:

.parent{ 
  display: grid;
  grid-template-columns: max-content max-content max-content;
  gap: 10px;
}

.child{
  width: 100px;
  height: 100px;
}

.child:nth-child(9n 1), .child:nth-child(9n 5), .child:nth-child(9n 9){
  background: blue;
}
.child:nth-child(9n 3), .child:nth-child(9n 4), .child:nth-child(9n 8){
  background: green;
}
.child:nth-child(9n 2), .child:nth-child(9n 6), .child:nth-child(9n 7){
  background: gray;
}
<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 ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

  • Related