skip navigation

Dark Mode

prefers-color-scheme

This media query is now one of the older ways to add a second scheme.

@media (prefers-color-scheme: dark) {
    :root {
		--code-bg: #655a5a;
		--text: #9cc8f7;
		--headercolor: #0668b0;
		--MainBorderColor: #3e4e5e;
		--container-bg: #2e3641;
		--body-bg: #222831;
	}
}

This says for users that have their OS set to dark these are the colours for each custom property (CSS variables).

HTML meta tag

<meta name="color-scheme" content="dark light">

This tells the browser that there are two colour schemes. The first, in this case dark is the preferred one which is used if the user has no preference set in their OS.

This helps the browser render the background colour immediately, without having to download and parse the whole css file first. This avoids a flash of full screen white which is helpful who prefer their screens muted.

See demo

The color-scheme property

The color-scheme property is usually placed in the :root section of your CSS:

:root {
    color-scheme: dark light;
}

light-dark()

The light-dark() colour function picks one of two colours based upon the the colour scheme of the user.

body {
    color: light-dark(#333, floralwhite);
    background-color: light-dark(floralwhite, black);
}

If the colour scheme is light then the first colour will be used. If dark then the second value is used.

Style queries

These are very new at the time of writing and not fully supported on any browser but partly supported (with CSS custom properties) on Chromium browsers.

These are part of container queries.

@container style(background: blue) {
    /* Not working at present */
}
    /* Only custom properties work */

@container style(--bg-color: blue) {
    background: white;
}

This says if the custom property --bg-color is set to blue then set the background to white.

As a container query this won’t look at specific elements but rather their parents or grandparents etc..

Please enter a search term