Convert Hex2RGBA For Your CSS Selectors

πŸ‘‹ Ciprian on Monday, July 8, 2019 in Blog
Last modified on Monday, July 8, 2019

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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. Last modified on Monday, July 8, 2019.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy