Home > Mobile >  add a specific css class to the two first elment then skeep the next two element and so one using ng
add a specific css class to the two first elment then skeep the next two element and so one using ng

Time:05-21

I have this code, to display list of products, using *ngFor in Angular:

<div >
  <div  *ngFor="let product of ['product A', 'product B', 'product C', 'product D']; let index = index">
    <div [ngClass]="{'color-gray': index % 2 === 0}">{{ product }}</div>
  </div>
 </div>

with this CSS:

  .container-products{ 
        display: flex;
        flex-wrap: wrap;
     }
     .item-product{
        flex: 50%;
     }
     .color-gray {
        background-color: gray;
     }

And I have the result like this: my table with color gray My question is what can I put instead index % 2 === 0 in the html to have the two first one in gray skeep the two next one and so one. Thank you.

CodePudding user response:

You can get the expected style with only CSS and nth-child:

div.item-product:nth-child(4n-3),
div.item-product:nth-child(4n-2) {
    background-color: gray;
}

With this you're making groups of 4 elements, and then taking:

  • The 4th element minus 3 (so the 1st of the group of 4)
  • The 4th element minus 2 (so the 2nd of the group of 4)

Example with your own code (with angular removed for clarity):

.container-products {
  display: flex;
  flex-wrap: wrap;
}

.item-product {
  flex: 50%;
}

div.item-product:nth-child(4n-3),
div.item-product:nth-child(4n-2) {
  background-color: gray;
}
<div >
  <div >
    <div>Product A</div>
  </div>
  <div >
    <div>Product B</div>
  </div>
  <div >
    <div>Product C</div>
  </div>
  <div >
    <div>Product D</div>
  </div>
  <div >
    <div>Product E</div>
  </div>
  <div >
    <div>Product F</div>
  </div>
  <div >
    <div>Product G</div>
  </div>
  <div >
    <div>Product H</div>
  </div>
</div>

  • Related