// basic hex to rgb converter
function hexToRGB(hex) {
const hexNormalized = hex.replace('#', '');
const red = parseInt(hexNormalized.substr(0, 2), 16);
const green = parseInt(hexNormalized.substr(2, 2), 16);
const blue = parseInt(hexNormalized.substr(4, 2), 16);
return `${red}, ${green}, ${blue}`;
}
// handling rgb and rgba values
function hexToRGBA(hex) {
const hexNormalized = hex.replace('#', '');
const red = parseInt(hexNormalized.substr(0, 2), 16);
const green = parseInt(hexNormalized.substr(2, 2), 16);
const blue = parseInt(hexNormalized.substr(4, 2), 16);
const alpha = hexNormalized.substr(6, 2);
let alphaPercentage = '100';
if (!!alpha) {
alphaPercentage = Math.round(parseInt(alpha, 16) / 0xFF * 100);
}
return `${red}, ${green}, ${blue}, ${alphaPercentage}%`;
}
// apply an alpha channel to your hex value
function hexWithAlpha(hex, alpha) {
const hexNormalized = hex.replace('#', '');
const alphaHex = Math.round(alpha * 0xFF).toString(16);
return `#${hexNormalized}${alphaHex}`;
}
// manually convert your hex into an RGB value and separate the values in the css property e.g. #56647B = rgb(86, 100, 123)
document.documentElement.style.setProperty('--col1', '86, 100, 123');
// add an alpha channel to your hex-value manually
// #56647B26 = rgba(86, 100, 123, 0.15);
// https://gist.github.com/lopspower/03fb1cc0ac9f32ef38f4
// https://caniuse.com/css-rrggbbaa
document.documentElement.style.setProperty('--col2', '#56647B26');
// convert hex to rgb with a helper function
document.documentElement.style.setProperty('--col3', hexToRGB('#56647B'));
// convert hex to rgba with a helper function
document.documentElement.style.setProperty('--col4', hexToRGBA('#56647B26'));
// add an alpha channel to your hex-value with a helper function
document.documentElement.style.setProperty('--col5', hexWithAlpha('#56647B', 0.15));
:root {
--col1: hotpink;
--col2: hotpink;
--col3: hotpink;
--col4: hotpink;
--col5: hotpink;
}
.container {
display: flex;
flex-flow: row nowrap;
gap: 15px;
}
.box {
width: 100px;
height: 100px;
}
.box-1 {
background-color: rgba(var(--col1), 0.15);
}
.box-2 {
background-color: var(--col2);
}
.box-3 {
background-color: rgba(var(--col3), 0.15);
}
.box-4 {
background-color: rgba(var(--col4));
}
.box-5 {
background-color: var(--col5);
}
<div class="container">
<div class="box box-1">Box 1</div>
<div class="box box-2">Box 2</div>
<div class="box box-3">Box 3</div>
<div class="box box-4">Box 4</div>
<div class="box box-5">Box 5</div>
</div>