Using CSS inside SVGs for dark mode

TIL SVGs support media queries... or <style> tags at all

Published

Edit: I undid this for reasons.

SVGs are crazy, I feel like I learn something new about them all the time.

I was just reading about some deeper complexities of SVGs that I didn't know about... While I agree that it's a deep dark hole, it does feel accasionally nice to learn about a feature that helps me do something more easily.

When creating the favicon for this website, I wanted to ensure it worked well enough for light and dark mode users alike. The site itself only has a "light" mode (sor far) but I didn't want the icon to disappear in different browsers.

Screenshot of favicon on light tab
Screenshot of favicon on light tab

Things get a little muddled when in dark mode, however...

Screenshot of favicon on dark tab
Screenshot of favicon on dark tab

SVG to the rescue

SVG fully supports the use of a <style> tag to leverage CSS within the image.

Combining that with a color scheme preference query, you get a fairly* natively supported scheme-aware favicon!

Mine looks like this:

<svg width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
<style>
path { fill: #000000; }
@media (prefers-color-scheme: dark) {
path { fill: #ffffff; }
}
</style>
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.5 0.0128479L11 3.80451V7.00001H8.70711L11 9.2929V12.1955L7.5 15.9872L4 12.1955V9.00001H6.29289L4 6.70711V3.80451L7.5 0.0128479ZM7 10H5V11.8045L7.5 14.5128L10 11.8045V9.70711L7 6.70711V4.00001H8V6.00001H10V4.1955L7.5 1.48717L5 4.1955V6.2929L8 9.2929V12H7V10Z" />
</svg>
svg

*Fairly natively supported...

Alright so using an SVG file as a favicon isn't 100% supported (Caniuse page), especially in new IE Safari 😑.

That's alright though, since we can fall back pretty gracefully to the globally supported .ico file type.

<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
html

Thanks for the tip, Chris.