Skip to content Skip to sidebar Skip to footer

Browsers Automatically Evaluate Hex Or Hsl Colors To Rgb When Setting Via Element.style.background?

I am not sure if I am missing something obvious but can somebody explain this to me? The following snippet is from what I did on Chrome DevTools Console. Same is the result for Fir

Solution 1:

As per the spec:

If the value is translucent, the computed value will be the rgba() corresponding one. If it isn't, it will be the rgb() corresponding one.

Meaning that no matter what is your input, the computed value always results in either rgb or rgba.

So, answering your question: yes, it is standard behaviour and no, you can't use hex or hsl as it will be computed back to rgba.

Solution 2:

My solution is... to use "outerHTML" ! It's the only place from where we can extract the genuine color format.

function realBkgColor(elem){
    let outer = elem.outerHTML.replace(/\s/g,'');
    let tag = outer.split('<'+elem.tagName).pop().split('>')[0];
    let style = tag.split('style="').pop().split('"')[0];
    let color = style.split('background-color:').pop().split(';')[0];
    return color;
}
div = document.querySelector('div');
div.innerHTML = realBkgColor(div);

returns "#ffff00" and not "rgb(255, 255, 0)"

<divstyle="background-color: #ffff00"></div><!--
<div style="background-color: rgb(255, 255, 0)"></div>
<div style="background-color: hsl(60, 100%, 50%)"></div>
<div style="background-color: yellow"></div>
-->

Try it with these...

Post a Comment for "Browsers Automatically Evaluate Hex Or Hsl Colors To Rgb When Setting Via Element.style.background?"