Skip to content

Instantly share code, notes, and snippets.

@shreshthmohan
Last active September 21, 2022 05:26
Show Gist options
  • Save shreshthmohan/3bbf2ad85a6abcf17321a933bf142441 to your computer and use it in GitHub Desktop.
Save shreshthmohan/3bbf2ad85a6abcf17321a933bf142441 to your computer and use it in GitHub Desktop.
Override user-agent dark mode styling with `prefers-color-scheme` media query
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark light" />
<title>
Override user-agent dark mode styling with `prefers-color-scheme` media
query
</title>
<style>
@media (prefers-color-scheme: dark) {
h2.dark {
color: #bae6fd; /* Default on Chrome is white (#fff) */
}
div.dark {
background-color: #27272a;
}
}
</style>
</head>
<body>
<h1>
This page shows how to override browser's default styling in dark mode. No
JS needed.
</h1>
<pre>
@media (prefers-color-scheme: dark) {
h2.dark {
color: #bae6fd; /* override the default dark mode text color white (#fff) */
}
}
</pre>
<h2>An h2 tag with browser's default color</h2>
<h2 class="dark">An h2 tag with prefers-color-scheme override</h2>
<div
style="width: 300px; padding: 20px; font-size: 1.2rem"
class="dark"
>
<p>Some text with custom <code>background-color</code> override.</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident
reprehenderit iste eius voluptas minima a beatae iure eos debitis optio?
Doloribus placeat, at minus odio neque numquam distinctio ipsam quam.
</p>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment