Home > OS >  Make every odd row different color than even row - Angular and CSS
Make every odd row different color than even row - Angular and CSS

Time:06-08

I want to make every other row different color. I am not sure what I am doing wrong, as it looks like it should work, but it colors me EVERY row with grey.

I am using angular, and I have parent and child component In my parent component I pass the data to the child component.

HTML is

 <div >
      <div *ngFor="let event of allEvents">
        <app-event-item
          [eventsList]="event"
        ></app-event-item>
      </div>
    </div>

And my CSS code of parent component

 .list-view {
      display: flex;
      flex-direction: column;
    }

Now in child component I get multiple arrays of event with data, which i passed to child component and loop through data with *ngFor

In html then I just display the rows of data.

HTML code of child component:

  <div >
    <img [src]="imageUrl" />
    <div >
      <h4>
        <a>{{ eventsList.title }}</a>
      </h4>
    </div>
    <div >
      <p>{{ eventsList.date }}</p>
    </div>
    <div >
      <p>{{ eventsList.count }}</p>
    </div>
</div>

Here is my css code in CHILD component

 .list-view {
    display: grid;
    grid-template-columns: 300px 45% 1fr 1fr;
    align-items: center;
    height: 100px;

    &:nth-child(odd) {
      background-color: #F9F9F9;
    }

    img {
      max-height: 100%;
      max-width: 100%;
      object-fit: cover;
      border-radius: 0.75rem;
    }

    .about-event {
      padding-left: 1rem;
    }
  }

It makes every row color #F9F9F9.

CodePudding user response:

you can use an Angular aproach:

<div >
      <div *ngFor="let event of allEvents;let odd=odd" 
             [style.background-color]="odd?'red':null>
        <app-event-item
          [eventsList]="event"
        ></app-event-item>
      </div>
</div>

CodePudding user response:

Try something like -

.list-view {
    display: grid;
    grid-template-columns: 300px 45% 1fr 1fr;
    align-items: center;
    height: 100px;

    &:nth-child(odd) {
      background-color: #F9F9F9; 
       }
    }

    img {
      max-height: 100%;
      max-width: 100%;
      object-fit: cover;
      border-radius: 0.75rem;
    }

    .about-event {
      padding-left: 1rem;
    }
  }

You missed a curly bracket, I think.

  • Related