Convert Hex2RGBA For Your CSS Selectors

on in Blog
Last modified on

I’ll just leave this here. It’s an old piece of code I used for a theme, where users selected a colour and then set a custom transparency value.

<?php
/**
 * Convert a Hexadecimal colour code to RGBA
 *
 * Converts a Hexadecimal colour code to RGB and returns an RGBA value.
 *
 * @param  string $color   Colour string
 * @param  string $opacity Colour opacity
 * @return string
 */
function supernova_hex2rgb($color, $opacity) {
    $color = trim($color, '#');
    $hex = hexdec($color);

    $r = hexdec(substr($color, 0, 2));
    $g = hexdec(substr($color, 2, 2));
    $b = hexdec(substr($color, 4, 2));

    return $r . ', ' . $g . ', ' . $b . ', ' . $opacity;
}
?>
<style scope="inline">
selector {
    background-color: rgba(<?php echo supernova_hex2rgb(get_option('header_background_colour'), '0.85'); ?>);
}
</style>

I have moved to CSS variable since then, but it’s still useful.

Related posts