SVG with Dark and Light Mode

Tuesday 20 February 2024

Dark and light mode is a feature that is supported by most modern web browser. This feature can be used in customizing SVG to be used in different mode.

To use dark and light mode in SVG, we can use the style tag. The style tag is used to specify how the components inside the SVG is styled.

<svg>
	<style>
		circle {
			fill: black;
		}
	</style>
	<circle
		cx="50"
		cy="50"
		="40"
	/>
</svg>

In this example, the circle is filled with black color.

With the media query, we can specify different styles for different light mode and dark mode.

<svg>
	<style>
		circle {
			fill: black;
		}

		@media (prefers-color-scheme: dark) {
			circle {
				fill: white;
			}
		}
	</style>
	<circle
		cx="50"
		cy="50"
		="40"
	/>
</svg>

In this example, the circle is filled with white color when the user's system is in dark mode. When the user's system is in light mode, the circle is filled with black color.

This is useful when we want to create a SVG that is optimized for both light and dark mode. The support for this prefers-color-scheme media query is good. According to caniuse, it is supported by more than 96% of the users.

Another useful usage of this feature is in favicon. The favicon using SVG with dark and light mode is supported by a lot of modern browsers but still less then 80%, around 76% according to caniuse. Therefore it is still good idea to have fallbacks for browsers that do not support it.