What I learned by creating a dark mode toggle
The short answer is: quite a lot. The long answer covers some accessibility issues, some new CSS, some slightly older CSS, some high level colour theory, a bit about SVGs, and some typography finessing; all of which I’ll cover in this post.
I had a few motivations for creating a dark mode toggle. Firstly I wanted a place to try out some variations in typography for inverted text (light and dark), as I embark on a second edition of my book. I also felt that having a dark theme available to anyone reading with those preferences was simply the right thing to do. And of course it was the joy of learning something new, particularly when I came across the light-dark() function.
Creating the theme switcher
The dark mode toggle, or theme switcher, sits in the header of this website. It gives the reader three options:
- Use their current system preference (default)
- Specifically set dark mode
- Specifically set light mode
It’s coded up using radio buttons and inline SVGs as follows:
<fieldset id="theme-switcher">
<legend>Theme</legend>
<label for="theme-system">
<input type="radio" name="color-theme" value="system" checked onchange="switchAuto()" id="theme-system">
<svg id="icon-system" fill="currentColor" width="1em" height="1em" viewBox="0 0 32 32" role="img">
<title>System default theme</title>
<path …></path>
</svg>
</label>
<label for="theme-dark">
<input type="radio" name="color-theme" value="dark" onchange="switchDark()" id="theme-dark">
<svg id="icon-moon" stroke="currentColor" width="1em" height="1em" viewBox="0 0 16 16" role="img">
<title>Dark theme</title>
<path …></path>
</svg>
</label>
<label for="theme-light">
<input type="radio" name="color-theme" value="light" onchange="switchLight()" id="theme-light">
<svg id="icon-sun" stroke="currentColor" width="1em" height="1em" viewBox="0 0 16 16" role="img">
<title>Light theme</title>
<path …></path>
</svg>
</label>
</fieldset>
There’s a few things to pick apart here.
Marking up the toggles
First of all why radio buttons? Well I could have used <button>s like on MDN on the basis that each option performs an action. I like the MDN user interaction, but to my mind these are exclusive options of the same thing, so radio buttons seemed more appropriate.
The SVGs are inlined rather than linked to with an img element. This give us the ability to style them dynamically, and for the SVGs to use keyword values pertaining to the webpage, in particular currentcolor. The SVG icons are sized in ems so they scale with the text. I’ve also given each SVG a <title>. This provides a visible tooltip, but it also gives us alternative text we can use as a label.
I wrapped each radio button in its own <label>, which I’ll make use of later. I thought this would be enough to associate the input with the SVG, but having tested with VoiceOver on Safari, it seems we still need to explicitly associate the two with for and id attributes. I also tried adding an aria-labelled attribute to the input, which pointed to the <title> in the accompanying SVG, but it proved unnecessary, although in order that the title is read out on iOS, I needed to add a role="img" to each SVG as well.
Styling the toggles accessibly
The first job was to visibly hide the <legend>, so I absolutely positioned it off screen:
#theme-switcher legend {
position: absolute;
left: -100vw;
}
Next I need to hide the radio buttons as I just wanted to show the icons. It turns out there’s a better way of hiding interactive elements than shifting them off screen. This involves positioning the input over the SVG icon, and then hiding it. It means that radio buttons can be findable to anyone exploring by touch.
Firstly I made use of that the label wrapper and set it to position: relative:
#theme-switcher label {
position: relative;
}
Next I set the input to the same size as the SVG, positioned it absolutely over the icon (tweaking its position slightly), and made its opacity fully transparent:
input[name="color-theme"] {
height:1em;
width:1em;
position: absolute;
left:-0.05em;
top:0.2em;
opacity: 0;
}
One final tweak was to position the icons so that they line up nicely with the navigation text also in the header. By ‘nicely’ I mean so that the middle of the SVG aligns with the middle of capital letters. By default, the middle of the SVGs would line up with the middle of the adjacent text box, meaning they sat too low. Therefore they needed nudging upwards, which in the past I might have done with a negative margin and a ‘magic number’. In modern CSS, that magic number can be reliably calculated as the difference between the x-height and the cap-height, so this neat translation did the job:
#theme-switcher label {
translate: 0 calc(0.5ex – 0.5cap);
}
Designing states
The radio buttons are now hidden, but that means I’ve also removed any sense of state for the inputs. I decided to use opacity as a way of introducing states (it might be a bit subtle, and maybe the contrast needs tweaking, but I think it works OK). First off I dimmed all the icons, changed the cursor and set up a smooth transition for the opacity:
#theme-switcher label svg {
opacity: 0.4;
transition-property: color, opacity;
transition-duration: 0.25s;
transition-timing-function: ease;
cursor: pointer;
}
Then I made sure the icons lit up on hover or when the radio button had focus:
#theme-switcher label:hover svg,
#theme-switcher input[name="color-theme"]:focus + svg {
opacity: 1;
}
And finally I made the current option brighter but visibly inert:
#theme-switcher input[name="color-theme"]:checked + svg {
opacity: 0.8;
cursor: auto;
}
Scripting the interaction
As we’ll see, the website automatically chooses light or dark mode depending on the user’s system settings (on MacOS you’ll find this in Settings under Appearance. In iOS it’s under Display & Brightness). In order for the user to specifically choose light or dark, overriding their system setting as necessary, a bit of JavaScript is required. There’s probably a pure CSS way to do this using has(), but I want to save the user’s choice for them, which requires JavaScript, so I’m considering the theme toggle as a progressive enhancement. What all this means is that I’m hiding the theme toggle from everyone:
#theme-switcher {
display: none;
}
Each radio button has an onchange event handler which calls a function like this:
function switchDark() {
document.documentElement.dataset.colorScheme = "dark";
localStorage.setItem("mode", "dark");
document.getElementById("theme-dark").checked = true;
}
The first line of the function switches out a data attribute on the root element data-color-scheme="dark". I use the data attribute in a selector to switch the CSS out for each mode. The next line sets a local storage item for the selected mode. This is the first time I’ve used local storage, and it’s so much easier than setting cookies. When the user selects the default mode, I just remove the local storage item, like this: localStorage.removeItem("mode"). The final line sets the state of the radio button. This is because I also call these functions once the DOM has loaded and if a mode has been set in the user’s local storage:
document.addEventListener('DOMContentLoaded', function(){
const mode = localStorage.getItem("mode");
if (mode === "light") switchLight();
if (mode === "dark") switchDark();
document.getElementById("theme-switcher").classList.add("visible");
})
At this point I also show the toggle again by adding a visible class. As we’ll see, my theming relies heavily on the new light-dark() function which at the time of writing is designated Baseline Newly Available with around 87% support, so its viable but can’t be fully relied upon. Therefore I only show the theme toggle when JavaScript turns it on and light-dark() is supported:
@supports(color:light-dark(#fff,#000)) {
#theme-switcher.visible {
display: flex;
}
}
Designing the light and dark mode themes
At this point I’ve made a toggle to switch dark and light modes, and store the user’s preference. The final job is to design those modes. But first we need to tell the browser that the website supports dark and light modes, which we do using the color-scheme property:
:root {
color-scheme: light dark;
&[data-color-scheme="light"] {
color-scheme: light;
}
&[data-color-scheme="dark"] {
color-scheme: dark;
}
}
Setting colour-scheme: light dark tells the browser the webpage supports both light and dark mode, and that it should check the user’s operating system settings for which one to use. The browser then applies appropriate default colours for aspects like the page background, text colour, form controls, scrollbars, and other system colours, without having to define those in the stylesheet.
The next rules check to see if the user has toggled a specific mode by matching a data-color-scheme attribute set on the root element, and overriding the color-scheme accordingly.
Next up is to define some colours, which I did using custom properties. To keep it short, here’s a few of them for the light theme, including the red ‘spine’ on the left side of the page:
--color-l-headfoot: hsla(0, 0%, 100%, 0.6);
--color-l-headfoot-bg: hsl(30, 3%, 26%);
--color-l-spine: hsl(0, 0%, 100%);
--color-l-spine-bg: hsl(3, 70%, 55%);
--color-l-page: hsl(0, 0%, 0%);
--color-l-page-bg: hsl(37, 10%, 85%);
--color-l-link-hover: hsl(3, 99%, 46%);
I use HSL (hue, saturation, luminance) to specify colours. As I’m red-green colourblind this really helps me know what colour something is – essentially that’s done with the first number which goes from 0–360 (degrees on a colour wheel), where red is at 0/360, yellow is at 60, green is at 120, blue is at 240 and magenta is at 300. It also makes it easy to try out complementary colours using some basic maths-based colour theory, which I have to do because I can’t trust my eyes to judge for themselves.
I mention HSL because it also makes it easy to come up with complementary dark mode colours. These is the same palette of colours adapted for my dark theme:
--color-d-headfoot: hsla(0, 0%, 100%, 0.6);
--color-d-headfoot-bg: hsl(30, 3%, 8%);
--color-d-spine: hsl(0, 0%, 100%);
--color-d-spine-bg: hsl(3, 60%, 30%);
--color-d-page: hsl(37, 10%, 85%);
--color-d-page-bg: hsl(30, 3%, 13%);
--color-d-link-hover: hsl(186, 99%, 46%);
In this case, for the header I kept the text colour the same but darkened the background (reduced the lightness from 26% to 8%). I kept the red spine, rather than trying to find its inverse colour, but reduced the saturation (from 70% to 60%) and darkened it (from 55% to 30%). For the main page, I used made the text the same colour as the light background and used a slightly lighter version of header colour. For the link focus and hover (in addition to underline) I did choose an inverse colour to the red I use in the light mode, changing the hue from 3 to 186 (the exact inverse of 183 didn’t look quite as good to me).
Having set up the two palettes using custom properties, these still needed to be made to work with the dark mode toggle. Firstly I set up more custom properties which would be used through the style sheet, and applied the light mode palette as a default. This for browsers that don’t yet support light-dark():
--color-headfoot: var(--color-l-headfoot);
--color-headfoot-bg: var(--color-l-headfoot-bg);
--color-spine: var(--color-l-spine);
--color-spine-bg: var(--color-l-spine-bg);
--color-page: var(--color-l-page);
--color-page-bg: var(--color-l-page-bg);
--color-link-hover: var(--color-l-link-hover);
Next job was to repeat the process using light-dark() to automatically swap palettes depending on the theme selected:
--color-headfoot: light-dark(var(--color-l-headfoot), var(--color-d-headfoot));
--color-headfoot-bg: light-dark(var(--color-l-headfoot-bg), var(--color-d-headfoot-bg));
--color-spine: light-dark(var(--color-l-spine), var(--color-d-spine));
--color-spine-bg: light-dark(var(--color-l-spine-bg), var(--color-d-spine-bg));
--color-page: light-dark(var(--color-l-page), var(--color-d-page));
--color-page-bg: light-dark(var(--color-l-page-bg), var(--color-d-page-bg));
--color-link-hover: light-dark(var(--color-l-link-hover), var(--color-d-link-hover));
Tweaking the text for dark mode
That’s the colours done (including the browser chrome thanks to using colour-scheme). But I also wanted to tweak the typography. When light text is rendered on a dark background, the text will often seem slightly bolder when compared to dark on light. Looking closely at the text on my site, this was certainly the case. The solution was to adjust the weight of the text.
Because I’m using a variable font, I could tweak the weights quite precisely, rather than more crudely step down from a ‘regular’ to a ‘light’ font. Ideally you would use a grade axis for this. Grade was designed precisely for this purpose – compensating for differences in appearance to bring the type back towards the intended design (albeit to cater for different types of paper). The main difference between grade and weight is that changing the grade doesn’t change the width of the characters, whereas an increase in weight will usually make the glyphs wider too. It also means you can adjust a grade axis on the variable font without needing to touch any font weights.
However not many typefaces include a grade axis, including the one I’m using at the time of writing, so I did need to adjust the weights. Through experimentation I found that if I reduced the weight by 15% I got parity in dark mode. I set up the dark mode factor as another custom property alongside the ones I’d already defined for font weights:
--weight-body: 400;
--weight-h1: 900;
--weight-h2: 700;
--weight-h3: 650;
--weight-h4: 600;
--weight-h5: 550;
--weight-h6: 500;
--weight-mono: 500;
--weight-factor: 1; /* default multiplier */
--weight-darkmodefactor: 0.85; /* reduce weight by 15% */
I then applied all these weights to the various elements, multiplying by the weight factor:
body { font-weight: calc(var(--weight-body) * var(--weight-factor)); }
h1 { font-weight: calc(var(--weight-h1) * var(--weight-factor)); }
h2 { font-weight: calc(var(--weight-h2) * var(--weight-factor)); }
h3, dt { font-weight: calc(var(--weight-h4) * var(--weight-factor)); }
h4, th { font-weight: calc(var(--weight-h4) * var(--weight-factor)); }
h5 { font-weight: calc(var(--weight-h5) * var(--weight-factor)); }
h6 { font-weight: calc(var(--weight-h6) * var(--weight-factor)); }
pre, code, var, samp, kbd { font-weight: calc(var(--weight-mono) * var(--weight-factor)); }
Finally I switched out the default weight factor for the dark mode one, firstly when the system default was set to dark mode (using the prefers-color-scheme media query), and secondly if the user and specified dark mode (reading the data attribute set on the root):
@media (prefers-color-scheme: dark) {
:root {
--weight-factor: var(--weight-darkmodefactor);
}
}
:root[data-color-scheme="dark"] {
--weight-factor: var(--weight-darkmodefactor);
}
This reminded me that the real power in CSS custom properties is not so much that you can set up a variable at the beginning of your stylesheet, but that you can use it as a toggle or switch at any point. Every Layout uses this to great effect.
The files
And that’s it. In case its of any help, I’ve compiled all the code I’ve gone through into individual files. You are always welcome to view source, but caveat emptor (all bug reports and suggestions welcome):
Credit where its due
No techniques in this blog post are new in isolation, but hopefully I’ve added usefully to the canon. I’ve borrowed significantly from the following people and articles:
- Mayank: CSS light-dark()
- Sara Joy: Come to the light-dark() Side
- Sara Soueidan: Inclusively Hiding & Styling Checkboxes and Radio Buttons
- Roma Komarov: Cap-Height Vertical Align
- Jon Hicks: Hue, Saturation, Lightness
- Andy Clarke: Redesigning your product and website for dark mode and Designing Zombie Hunt part two: Dark and light themes