Damiano Damiano - 1 year ago 92
jQuery Question

Why jQuery replaces hsl() with rgb()?

I wanted to add some spans dynamically with hsl background-color applied to style attribute, like this:

<span style="background-color: hsl(190, 75%, 43%)"></span>

Here is my jQuery doing this:

var hues = [ 172, 178, 184, 190, 196, 202, 208 ];

$.each(hues, function(index, backgroundHue) {
var newSpan = $('<span></span>');
newSpan.css('background-color', 'hsl('+backgroundHue+', 75%, 43%)');

But as a result i got span with rgb() background color (auto-converted from hsl()):

<span style="background-color: rgb(27, 165, 192);"></span>

Here is a fiddle: https://jsfiddle.net/pbjcvwdh/5/

Can anyone explain why is this and is there any way to avoid this auto-conversion? If I apply background-color statically in html it doesn't change to rgb().

Answer Source

jQuery has nothing to do with this behaviour - it's simply because browsers render the value in RGB format. You can't change it unfortunately. If you want to get the value in HSL format you need to convert it back from RGB. This question can help you with that, if required.

To prove the above, here's a native JS implementation that exhibits the same behaviour:

[172, 178, 184, 190, 196, 202, 208].forEach(function(backgroundHue) {
  var span = document.createElement('span');
  span.style.backgroundColor = 'hsl(' + backgroundHue + ', 75%, 43%)';
.add-em-here span {
  display: inline-block;
  height: 40px;
  width: 40px;
  border: 2px solid white;
  margin-left: 6px;
<div class="add-em-here">
  <!-- Added statically - stays with hsl() -->
  <span style="background-color: hsl(60, 75%, 43%)"></span>

  <!-- Added dynamically - auto-replaced with rgb() -->

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download