Skip to content

Instantly share code, notes, and snippets.

@BSoDium
Last active September 8, 2022 08:46
Show Gist options
  • Save BSoDium/9354cd6f448a8fc7c11bddaa70fb4824 to your computer and use it in GitHub Desktop.
Save BSoDium/9354cd6f448a8fc7c11bddaa70fb4824 to your computer and use it in GitHub Desktop.
A simple script to add the mkdocs material sponsors only system theme feature
/**
* Set the data-md-color-scheme property on the body element to "slate" or "default"
* depending on the browser's preferred color scheme.
*/
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", function (e) {
var colorScheme = "default";
if (e.matches) {
colorScheme = "slate";
}
document.body.setAttribute("data-md-color-scheme", colorScheme);
});

Installation

Simply add the previous mkdocs configuration to your mkdocs.yml (only the palette field is important if you want your page to have a theme toggle button). Then, proceed to create a new file named extra.js in the same directory as the one mentioned in the mkdocs config file (extra_javascript field).

This is pretty much it, feel free to suggest any modifications by commenting on this gist.

theme:
name: material
logo: img/logo.png
favicon: img/favicon.ico
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
primary: teal
scheme: default
toggle:
icon: octicons/sun-16
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
primary: teal
scheme: slate
toggle:
icon: octicons/moon-16
name: Switch to light mode
extra_javascript:
- js/extra.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment