Search code examples
cssvariablesforeachrowbackground-color

Change background-color for each row using a color list Vue.js


I'm currently listing some colors. Each row has two spans, one with the color Id and the other is going to show a sample of the color.

   /* HTML */ 

     <ul>
         <li v-for="(ColorsList, index) in Colors" :key='index'>
            <span>{{ColorsList.COLOR_ID}}</span>
            <span class="test">{{ColorList.COLOR_HEX}}"></span>
         </li>
    </ul>


/* CSS */
.test {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin: auto auto;
 background-color:  var(--COLORHEX);
}

I need to use the hex to paint the background-color of the span, one approach I've found is to use a variable in css. But this changes all the spans in the list when each row should have a unique color. Any kind of help is much appreciated. Thanks !


Solution

  • You're using the same class for all <span class="test"> elements, and that leads to the same styles for all spans.

    Actually in your case, it should be fairly acceptable to use inline styles without the complexity of variables in css. Consider changing it to:

        <ul>
             <li v-for="(ColorsList, index) in Colors" :key='index'>
                <span>{{ColorsList.COLOR_ID}}</span>
                <span class="test"
                 v-bind:style="{ backgroundColor: ColorList.COLOR_HEX }" // note this inline style binding
                 >{{ColorList.COLOR_HEX}}"></span>
             </li>
        </ul>