Convert Hex2RGBA For Your CSS Selectors

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.

Added by Ciprian on Monday, July 8, 2019 in Blog

Unlimited Automated Page Speed Monitoring & Tracking.
Use SpeedFactor to track your website. It’s simple and reliable.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles

Privacy Policy