Skip to content

Dark mode for SVG #1058

@o-t-w

Description

@o-t-w

Description

For inline SVG currentcolor and CSS variables are simple ways to implement dark mode. When SVG is used like a typical image format as the src for an <img>, neither of those approaches work. There are two solutions: the light-dark() function or the prefers-color-scheme media query.

light-dark() CSS function

<svg style="color-scheme: light dark;" fill="light-dark(black, white)" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="5" r="5"/></svg>

light-dark() for non-inline SVG works in Firefox and Chromium. I opened a bug in Safari. There is a pull-request that has never been merged.

prefers-color-scheme media query

The prefers-color-scheme media query can be used inside of a <style> block inside an SVG:

<svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
  <style>
    rect { fill: black; }
    @media (prefers-color-scheme: dark) {
      rect { fill: white; }
    }
  </style>
  <rect width="32" height="32"/>
</svg>

The prefers-color-scheme media query works for non-inline SVG in Chrome/Edge and Firefox, but not in Safari. There is an open bug.

The results of this media query should be effected by the color-scheme CSS property.

<div style="color-scheme: light">
  <img src="/square.svg">
</div>
<div style="color-scheme: dark">
  <img src="/square.svg">
</div>

Unlike other browsers, Safari does not support light-dark() for <use>. This should also be fixed. All browsers seem to have issues with the prefers-color-scheme media query when used in conjunction with <use>.

Specification

https://www.w3.org/TR/css-color-5/#light-dark

web-feature

No response

Test Links

No response

Additional Signals

There are several popular articles about dark mode SVG favicons. The latest version of Safari supports SVG for favicons but does not support dark mode.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions