PROWAREtech

articles » current » css » detect-dark-mode

CSS: Detect Dark Mode

Using CSS @media query to detect if user is using dark mode theme.

This article shows how easy it is to detect if a user is requesting a dark theme. This requires CSS.

As of this writing, Chrome, Safari and Firefox support this media query; Edge (Windows 10 1909) and IE11 do not.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title></title>
	<style>
		/* NOTE: default formatting to light mode */
		body {
			background-color: #eee;
			color: #222;
		}
		/* NOTE: use media query to detect if dark mode is in use */
		@media (prefers-color-scheme: dark) {
			body {
				background-color: #000;
				color: #eee;
			}
		}
	</style>
</head>
<body>
	<h1>Lorem</h1>
	<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Et, libero.</p>
</body>
</html>

Coding Video

https://youtu.be/W6mvCL2vCC8

Alternate Version

Here is an alternate and very powerful version.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title></title>
	<style>
		/* NOTE: default formatting to light mode */
		body {
			background-color: #fff;
			color: #333;
			padding: 10px;
		}
		h1 {
			color: dodgerblue;
			box-shadow: rgba(0,0,0,.4) 5px 5px 5px;
			text-shadow: 8px 8px 2px #000;
			padding: 10px 0;
		}
		/* NOTE: use media query to detect if dark mode is in use */
		@media (prefers-color-scheme: dark) {
			* {
				filter: invert(1);
				box-shadow: none !important;
				text-shadow: none !important;
			}
			h1, img { /* NOTE: add any others to exclude from invert filter */
				filter: invert(0);
			}
		}
	</style>
</head>
<body>
	<h1>Lorem</h1>
	<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Et, libero.</p>
</body>
</html>

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE