I have a site where you can change the background-color
of sections. Usually I do this by having a radio button and based on this I append a class to that element. Now I thought to be adventures and use the color picker, because I don’t know what the colors are going to be jet.
What I was thinking was if you can check the hex color on how dark or light is it and based on that add a class so you know when to make the text white instead of black. Is there a way to achieve this with ACF or do I need to look for a separate color interpreter.
As a example for what I mean is a Atom plugin called Pigments which automatically highlights the color being used in a document. And it looks like this:
For the color white is text is black and for the color black the text is white, there seems to be some logic here.
Hi @mvaneijgen
I’m afraid ACF doesn’t have this kind of feature, so you need to create the logic yourself. There are a lot of discussions similar to this topic on the internet, and one of them is this one: http://serennu.com/colour/rgbtohsl.php.
I hope this helps 🙂
I created a function based on a Stack overflow answer (can’t find the page anymore otherwise I would have linked to it).
function get_darker_or_light_class_based_on_hex ( $hex_color ) {
$hex = str_replace( '#', '', $hex_color );
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
if($r + $g + $b < 450){
$class = 'dark-bg';
}else{
$class = 'light-bg';
};
return $class;
}
I had to change the 450
value to get it to work with my colors. And in my template part I use <?php echo get_darker_or_light_class_based_on_hex(get_sub_field('bg-color'); ?>
to get the right background class.
Hope someone finds this usefull.