1

I am trying to find how to change the row color of even rows so it alternates between odd and even indexes in my list of divs so odd would be a background of say white and the evens would be a background of gray. Is it possible to do this lwc for:each?

1 Answer 1

2

It is possible via CSS pseudo-class nth-child(), which matches elements based on their position among a group of siblings and allow keywords even and odd.
Just give a CSS class to your row and set the background color you want in CSS file using .className:nth-child(even) and .className:nth-child(odd) selector.

CSS

.row:nth-child(even) {
    background-color: grey;
}
.row:nth-child(odd) {
    background-color: white;
}

HTML

<div>
    <template for:each={list} for:item="elem">
        <div key={elem.id} class="row slds-var-p-around_small">
            {elem.label}
        </div>
    </template>
</div>

Here's a demo

1
  • Thank you RubenDG!!! Mar 2, 2022 at 16:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .