In the process of implementing this blog, I thought of having tags associated with the posts. This allows me to categorize the posts. However, I did not want to implement a very complex system that allows to manage the color, define which tags exist, etc, but wanted to have a color associated with each tag.
The tags of the post are stored with each post, and no color is save in the database. The focus here is how to get the color for the tags. The implementation I came up with was to hash the tag, and use the value to define the color. The following piece of code is what is used by this blog to create the color of tags like Code and Color.
function tagColor($tag) {
$m = md5(strtolower($tag));
$h = floor(hexdec(substr($m, 0, 4)) / 65535 * 359);
$s = (hexdec(substr($m, 4, 2)) % 32) + 69;
$l = (hexdec(substr($m, 6, 2)) % 16) + 75;
return 'hsl(' . $h . ', ' . $s .'%, ' . $l . '%)';
}
In order to have more control of how the final look of the tag looks like the HSL color model was used, because the lightness needs to be high to have a good contrast with the tag text color. Since the hue is a value between 0 and 359, a single byte from the hash is not enough to get the full range, so I use 2 bytes to get the hue, and scale it from [0, 65535] to [0, 359]. For the saturation and lightness, we sample 1 byte for each of them, and do some more math to get a good value. The saturation, uses 32 modulo to get a value from [0, 31] plus a the predefined value in this case 69, which makes for a good range [69, 100] in the saturation. In the case of the lightness the modulo 16 is used to have a lower range [75, 90] of lightness values when the predefined value of 75 is added.
A few optimizations could be done here, to get the values faster, but the code is about simplicity, and understanding how the color for the tags can be created from the tag itself.
This creates a simple, yet effective system of tags, which have the same color across the posts, even though the color is not stored anywhere. If you liked this post or have any question, feel free to hit me up on twitter @AndreBaltazar.
Thanks for reading!