Semantic HTML for Colors
One thing that design systems, style guides, and, uh I guess the content of your website if you sell paint all do at some point is display the colors available in a palette.
Usually with <div style="background-color: …">
, but I think we can do better than that. My vote goes to:
<label>My favorite shade of raspberry:
<input type="color" disabled value="#bf1942"/>
</label>
It’s a color. Semantically.
You can give it a name with
<label>
.Its value is accessibly exposed by assistive technology.
It will show up as the correct hue no matter the accessibility settings, like High-Contrast Mode. Color inversion mode should also have some special dispensation for it.
User stylesheets leave it be. (Yes, people use those. Check out Stylish/Stylus.)
With
appearance
and some goofity::-webkit
pseudo-elements, you can style it just fine.
(I’d prefer readonly
to disabled
— which even seems to work in most browsers — but sadly the spec only allows the readonly
attribute on other types of <input>
.)
Are you kidding me Safari
So like, it’s somewhat expected that IE11 isn’t down with the input[type=color]
, but Safari? It’s in the next version as of this writing… on desktop only.
Anyway, this is the next best thing:
<figure>
<figcaption>My favorite shade of raspberry:</figcaption>
<svg width="3em" height="3em" aria-label="#bf1942">
<rect fill="#bf1942"
width="100%" height="100%"/>
</svg>
</figure>
Bleh, though.
This does have the advantage of showing off colors that don’t fit within hex codes, though. The fill
attribute has bonus flexibility:
- Keywords like
peachpuff
andtransparent
- Other, more human-friendly syntax like
hsl()
- Semitransparent colors with
rgba()
and even the new#rrggbbaa
syntax - Or even pattern and gradient swatches with SVG’s
<pattern>
<linearGradient>
, and<radialGradient>
!
You know what’s worse? Desktop Safari still don’t support <input type="date">
. If only macOS had some sort of date picker built in.