Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different border-color for each flexbox item

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 class="slider">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div> 
  <div></div> 
  <div></div> 
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading