HSL color selector using HTML5 and CSS

Problem

Working on a project that required a color selector. The design calls for a gradient selector, but it’s pretty flexible on how we actually implement it. No problem, there’s a ton of libraries and plugins and modules and extensions and whathaveyou out there for doing color selectors.

However, I know HTML5 in its glory has an . As a bonus, this project only has to work in very new browsers (Safari 5.1 & Chrome), so I was stoked, thinking this would Just Work™. Turns out, it doesn’t. Now I’m bummed that I can’t do a really clean, simple, one-line solution, and all the libraries, plugins, modules and extensions are looking bulky and gross to me.

Solution

Safari 5.1, Chrome, & Opera do support background gradients, and the HTML5 input type=range. So we combine these two things using a span and a range selector. The span’s background is an HSL gradient with six color stops, evenly spread from red to violet. The range selector includes values from 0-300. We size the elements to be the same width, and position the range selector so it slightly overlaps the bottom of the gradient.

Now, the range selector corresponds to a hue value on the gradient, (we’re using the same saturation and luminosity throughout our gradient), so we can determine our color just from a simple integer value.

Code

<style>
  .spectrum {
    display: block;
    width: 150px;
    height: 15px;
    margin: 0 0 -3px 7px;
    background: -webkit-linear-gradient(left, hsl(0,100%,50%),hsl(60,100%, 50%), hsl(120,100%, 50%), hsl(180, 100%, 50%), hsl(240,100%,50%),hsl(300,100%,50%) 100%); 
  }
  input[type=range] {
    width: 161px;
    margin-top: -5px;
  }
</style>
<span class="spectrum"></span>
<input type="range" min="0" max="300" step="1">

</code>

Example


And here’s a screenshot for those who are using less-fancy browsers: Fancy color selector

Apology

This doesn’t look so hot in Firefox, yet.

Photo of Matt Slack

Long a secret weapon at Collective Idea, Matt has been involved with Collective Idea projects since the beginning. He’s our resident web front-end master (webmaster?) who can knock out CSS and HTML faster than you can think.

Comments