Search code examples
javascriptcsscssomcss-houdini

CSS Typed OM -- parsing background color?


const box = document.getElementById('rb');

console.log(box.computedStyleMap().get('background-color'))
.red {
  background-color: #FF0000;
}

.box {
  width: 100px;
  height: 100px;
}
<div id="rb" class="box red"></div>

Using the new CSS Typed Object Model, I'm trying to get the background color of this div. It gives me back a CSSStyleValue which only seems to have a toString() method. I was hoping it would parse the color into an RGB triplet or something else useful like it does for widths.

Is there an API for parsing colors, or has this not been specced out yet?

(I know I can parse the string by hand, that's not the question)


Solution

  • There is now a CSSColorValue interface being defined.
    It is currently available in Chrome under the experimental web platform flag, but apparently only for RGB and HSL colors.

    You can access such an object through CSSColorValue.parse(expr).

    This interface is the parent class of the CSSRGB, CSSHSL, CSSHWB, CSSLCH, CSSLab, and of the CSSColor interfaces.

    Each object has different signatures to represent its various components.

    For instance, CSSRGB is used for representing an rgb(), rgba() or a named color. Its r, g, and b properties are CSSUnitValue objects (an object with a value and an unit property) representing either a 0-255 number or a 0-100 percentage. Its alpha property is a 0-100 percentage CSSUnitValue.

    CSSHSL will be used for representing an hsl() or hsla() color. Its h property is a 0-360 CSSColorAngle object, and its s, and l and alpha properties are 0-100 percentage CSSUnitValue.

    And so on for every color representation (of note, CSSColor represents the color() function).

    So it's still not a single representation for any color value, but that's because it can't actually be done. Some colors can't be mapped to other notation directly. This still offers a way more convenient way to parse colors than dealing with string parsing ourselves.



    Note: This answer has been heavily edited in 2024, after being accepted and receiving 3 upvotes, because it became factually wrong:
    It made the claim that getComputedStyle would always represent colors as either rgb() or rgba() strings, this has been changed since then and for instance lab() colors will be returned as "lab(...)", not as "rgb(...)".