How to generate colors to group items by color?

时间:2017-04-09 23:21:08

标签: javascript css colors

I have groups of items, like:

<div data-group="1">Item</div>
<div data-group="1">Item</div>
<div data-group="1">Item</div>

<div data-group="2">Item</div>
<div data-group="2">Item</div>

I want to change the background color by group so I can tell them apart. But the background can't make the text unreadable.

I don't expect to have over 20 groups.

Is there a way to generate background colors that will always work with #000 text?

Or a way to know if it will work better with #000 or #fff text so I can flip the text color if needed?

Or should I give up the idea to make it dynamic and just pre-allocate 20 colors (like Trello does for labels)?

1 个答案:

答案 0 :(得分:1)

I would recommend using a predetermined list of colors, because you not only want the text to be legible on the background, but you also want the groups to be distinguishable from one another. If you have usability concerns, you might for instance want to shy away from colors that will look too similar to colorblind users. For more information see: http://www.somersault1824.com/tips-for-designing-scientific-figures-for-color-blind-readers/. That article contains a list of 15 colorblind safe colors that are distinguishable from one another.

You can then use something like the following jquery code (if jquery is available) to assign it:

var colorList = [colors...]
​
$('div').css('background-color', function(){
   return colorList[this.getAttribute('data-group')]
})