Praveen Puglia
Praveen Puglia

Reputation: 5631

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 Firefox.

> let container = document.createElement("div")
> undefined
> container.style.background = "#bbb"
> "#bbb"
> container
> <div style=​"background:​ rgb(187, 187, 187)​;​">​</div>​
> container.style.background = "hsl(120, 50%, 50%)"
> "hsl(120, 50%, 50%)"
> container
> <div style=​"background:​ rgb(63, 191, 63)​;​">​</div>​

Here's the image for better readability.

Is this the standard behaviour? If so, how do I get to put the real HEX or HSL value in inline style?

enter image description here

Upvotes: 6

Views: 3772

Answers (2)

RGill
RGill

Reputation: 1

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)"

<div style="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...

Upvotes: 0

jpedroribeiro
jpedroribeiro

Reputation: 642

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.

Upvotes: 6

Related Questions