4

How to set hsl color on CSSStyleDeclaration object?

//CSS
background-color: hsl(155,100%,30%);

//JavaScript
divElement.style.backgroundColor = ?;

I don't want to use HEX value or color name in javascript.

Please suggest.

W3C standard link would be a great help too.

i hesitate to set hsl string as I didn't find it in W3C CSSOM or DOM standard.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
P K
  • 9,972
  • 12
  • 53
  • 99

2 Answers2

15

Just set it as a string

divElement.style.backgroundColor = "hsl(155,100%,30%)";

Demo: http://jsfiddle.net/maniator/gg7JN/

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • Adding to this, it should be noted that in the DOM it seems that this is always converted back to RGB. Even when setting the `style` property string manually. I don't know however whether that behaviour is defined in the spec, or if it is just the browsers behaviour. It may cause some issues when you need the HSL declaration (eg. what you want to ony animate the Hue value). – Tarulia Apr 15 '17 at 07:48
  • 1
    setting a `hsl` code in jest test is not accepted? If `rgb` is set it works fine – Gaurav Soni Feb 20 '19 at 07:15
3

You want the w3 standard, section 4.2.4.

Examples copied from the site:

  • { color: hsl(0, 100%, 50%) } /* red */
  • { color: hsl(120, 100%, 50%) } /* lime */
  • { color: hsl(120, 100%, 25%) } /* dark green */
  • { color: hsl(120, 100%, 75%) } /* light green */
  • { color: hsl(120, 75%, 75%) } /* pastel green, and so on */

Note: I'm not saying Neal's answer is wrong - you can simply use an hsl string as Neal said. These examples are for css files.

The actual line you want that allows you to use css-style hsl as easily as hash colors or rgb is standard section 4.0, which simply says:

A <color> is either a keyword or a numerical specification.

The sections after that then define the types of colors: keywords (fuchsia), hash format (#ffcc88), rgb/a format (rgba(255,255,255,0.1)), or hsl/a format (hsla(0, 100%, 50%, 0.9)). Any of these can be used any time a css color is needed.

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76