Home > Enterprise >  How do I dynamically add CSS classes to HTML elements if value is less or greater than 0?
How do I dynamically add CSS classes to HTML elements if value is less or greater than 0?

Time:02-12

How can I dynamically add css classes to the <div > elements based on whether or not the value of the element is greater than 0?

HTML:

<template> <div >
        <div >
          <div v-for="(value, key) in coins" :key="value" >
            <div >
              <img src="{{ }}" >
              <div >{{key}}</div>
              <div >USDT</div>
            </div>
            <div >
              <div id="coin__row-small-div">
                <div >{{value.USD.PRICE}}</div>
                <div >{{value.BTC.PRICE}}</div>
              </div>
              <div id="coin__row-small-div">
                <div >{{value.USD.CHANGEPCTHOUR}}%</div>
                <div >{{value.BTC.CHANGEPCTHOUR}}%</div>
              </div>
            </div>
          </div>
        </div> </div>

</template>

Styles:

<style scoped>
      .positive {
        color: green;
      }
    
      .negative {
        color: red;
      }
    </style>

CodePudding user response:

You should try binding class. Something like that:

<div :>

and inside methods:

getDivClasses(value) {
  return value > 0 ? "positive" : "negative";
},
  • Related