I’m working on a web based chat application where I needed different colors for the speech bubbles. These are generated completely using CSS and consist of 5 different colors for text, gradient and border.
The problem that I faced is that they should be available in various colors and because each color required ~30 lines of code (only for the color definitions) I didn’t want to manually create each color.
Unfortunately, the RGB color model which is normally used in CSS color definitions is not very helpful. Take the gradient of this blue speech bubble: It goes from
rgb(87, 196, 255) to
rgb(168, 225, 255). There does not seem to be any logical relation between these two values.
This is where the HSL color model is a lot more useful. Instead of using Red, Green and Blue to describe Colors, the HSL color model uses Hue, Saturation and Lightness. The HSL Color Picker makes this clear:
The same two colors mentioned before have now the values
hsl(201, 100%, 67%) and
hsl(201, 100%, 83%). So while Hue and Saturation stay the same, only the lightness changes.
When I figured this out, I guessed that I’m not the first to find out and that I would probably find many great solutions to use this in PHP.
I was wrong.
Maybe I didn’t search long enough but I didn’t find any PHP script that did exactly what I wanted and was comprehensible (I didn’t want to use a code snippet that magically does what I want, without knowing, how it does.).
So I started to improve and extend what I found and ended up with a pretty nice set of PHP functions.
The Workflow looks like this:
Hex color code → RGB → HSL → Change Lightness → RGB → Hex color code
So we take an RGB hex color code, convert it to HSL, set the lightness to a desired level, convert it back to RGB and then generate a HEX color code from that.
You can download the ready-to-use PHP file with these functions (including an example how to use it) on GitHub:
Download RGB-HSL Converter