Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring the text depending on numeric value using css

Tags:

html

css

I want to color text based on its value, using css.

ie. if value is less than 20 --> red ,
    if value is between 20 - 60 --> orange , 
    if value is greater than 60 to 100--> green.

I don't want to add any class in the template depending on the value.

I found this Link: How do I change the background color with JavaScript? but it doesn't suffice as I have too many values to apply color to. Also I want it to be more maintainable when adding new values in future.

like image 927
anandharshan Avatar asked Aug 04 '15 07:08

anandharshan


1 Answers

It is not possible only with CSS.

You have to use JavaScript/jQuery to dynamically add the color, based on an object color match, and test if the value in the data-color HTML attribute is between the range for each element.

The JS code dynamically check if the element attribute is in a color range and apply the matched color.

If you will have to add some color and range in the future, simply add new values in the colorMatch hash, and update your CSS color class list.

##CSS

.red {color:red}

###HTML

<p data-color="19">Lorem 19</p>

###JS

var colorMatch = {
    '0-19'     : 'red',
    '20-59'    : 'orange',
    '60-100'   : 'green'
 };

Here is the working fiddle

like image 121
Giacomo Paita Avatar answered Nov 03 '22 01:11

Giacomo Paita