Bastian Venthur
Bastian Venthur

Reputation: 16570

Loading CSS based on prefers-color-scheme media query

If I want to split my CSS into two files, one for dark mode and one for light mode, how do I conditionally load them without using java script but only html?

I couldn't find any examples on https://developer.mozilla.org, like so?

<link rel="stylesheet" href="/light.css" type="text/css" media="(prefers-color-schme: light)">
<link rel="stylesheet" href="/dark.css" type="text/css" media="(prefers-color-schme: dark)">

Upvotes: 2

Views: 1366

Answers (2)

Peter Pointer
Peter Pointer

Reputation: 4162

Loading CSS based on any media query expression seems to be out of specification for the media attribute.

You can find valid values for the media attribute here, for example:
https://www.w3schools.com/tags/att_link_media.asp

It only allows certain ones for the media attribute, like: width, color, orientation, etc. See tables in the link above.

Best practice is to load all CSS including media queries directly. Loading all styling at once at the beginning means the browser can have it all in memory and draw elements very quickly.
Loading every media query separately would mean evaluating which CSS file to request from the server while the user rotates their tablet for example, which causes some lag and can look like jittery movement on the page and feel wrong.

You might think loading the extra couple kB for the media queries CSS is a problem. But putting all styles in a couple files means:

  1. Fewer TCP connections to wait on
  2. Compression during transport is more efficient
  3. If your styles stay the same they will be cached browser-side and only requested once anyway

Upvotes: 1

Rishi Ghosh
Rishi Ghosh

Reputation: 13

You cannot do that in html however inside the css file you can put everything in a

@media(prefers-color-scheme: light) {}

or

@media(prefers-color-scheme: dark) {}

Upvotes: 0

Related Questions