Home > Blockchain >  Different border-color for each flexbox item
Different border-color for each flexbox item

Time:02-17

How can I add different border-color for flexbox items. The flex items will be added dynamically, 5 different border-colors has to be applied to the items. The flexbox items need to start with the border-color red, then the next flexbox item with border-color orange, yellow, pink, green, and then start with the red and repeat the same border-color order again.

I tried nth-child but it does not start with the color red again.

.slider {
  display: flex;
  gap: 20px;
  flex-direction: row;
}

.slider > div {
    height: 50px;
    width: 50px;
    background-color: blue;
  }

.slider > div:nth-child(1n 0) {
  border: 5px solid red;
}
.slider > div:nth-child(2n 0) {
  border: 5px solid orange;
}
.slider > div:nth-child(3n 0) {
  border: 5px solid yellow;
}
.slider > div:nth-child(4n 0) {
  border: 5px solid pink;
}
.slider > div:nth-child(5n 0) {
  border: 5px solid green;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div> 
  <div></div> 
  <div></div> 
</div>

CodePudding user response:

The issue here is in your nth-child formula. Currently, you're looking for multiples of 1, then multiples of 2, then of 3, and so on. What you want is the remainder of n when divided by 5. Here is the relevant CSS with the corrected formulas:

.slider > div:nth-child(5n 1) {
  border: 5px solid red;
}
.slider > div:nth-child(5n 2) {
  border: 5px solid orange;
}
.slider > div:nth-child(5n 3) {
  border: 5px solid yellow;
}
.slider > div:nth-child(5n 4) {
  border: 5px solid pink;
}
.slider > div:nth-child(5n 5) {
  border: 5px solid green;
}
  • Related