Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Activate dark mode if 'prefers-color-scheme: dark' is supported and preferred, and/or toggle the dark mode using a button.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>HMTL template</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
/* just to see a nicer demo */
@import url("");
body {
padding: 0 2rem 2rem 2rem;
font-family: sans-serif;
button {
padding: 1rem 2rem;
cursor: pointer;
/* add a basic dark color combination */
body.dark {
background-color: black;
color: white;
<button class="dark-mode-switcher" type="button" value="Toggle dark mode">
Dark or light?
<script src=""></script>
// activate dark mode if 'prefers-color-scheme: dark' is supported and preferred
// ..or toggle dark mode using a button
var prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
$(function() {
if (prefersDark) {
$('.dark-mode-switcher').on('click', function(e) {

This comment has been minimized.

Copy link
Owner Author

marcop135 commented Jan 14, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.