Tailwind: from green to red color depend on percentage using Tailwind css

Viewed 351

I need background color map from green to red based on a progress variable (like in this fiddle).

function getColor(value){
    //value from 0 to 1
    var hue=((1-value)*120).toString(10);
    return ["hsl(",hue,",100%,50%)"].join("");
}
var len=20;
for(var i=0; i<=len; i++){
    var value=i/len;
    var d=document.createElement('div');
    d.textContent="value="+value;
    d.style.backgroundColor=getColor(value);
    document.body.appendChild(d);
}

As already answered here on Stackoverflow but using Tailwind CSS. Is that possible?

1 Answers

The current solution, generates color value on the fly. To fake such effect with Tailwindcss, I think it is reasonable to make a set of 11 colors to use. They can be called color-range-0, color-range-1,...color-range-10 and then in assign them directly by making this modification:

//old:
d.style.backgroundColor=getColor(value);

//new:
d.classList.add("bg-color-range-" + i);

and this is what should go to tailwindcss config file:

module.exports = {
  theme: {
    extend: {
      colors: {
        "color-range": {
          0: "#00FF00",
          1: "#33ff00",
          2: "#66ff00",
          3: "#99ff00",
          4: "#ccff00",
          5: "#ffff00",
          6: "#ffcc00",
          7: "#ff9900",
          8: "#ff6600",
          9: "#ff3300",
          10: "#ff0000",
        }
      },
    },
  },
  variants: {},
  plugins: [],
}

Result would be something like this:

enter image description here

Just keep in mind if you are using postcss to remove unused styles, you need to keep the name of these styles somewhere in comments in your html file.

Related