Chapter 6: Light/dark theme and switcher
We'll combine the about, projects, and footer sections into a single CodePen. Then we'll add the light/dark switching, which will work with the operating system and then with a user control.
6a: Combine sections into a single page
We'll start with our projects pen that we just finished. That's because it contains all CSS we've written so far. Here are the pens you'll need to combine:
- Beginning CodePen(the projects pen we just finished)
- Finished About CodePen
- Finished footer CodePen
From our final finished combined CodePen, we could call an end to development. You could move this whole site to VS Code, then Github and Github pages, which we will do in the next chapter. But we’re going to add one final piece of sizzle, which is a light/dark theme that’s only CSS driven. If you've had enough coding, feel free to skip ahead.
6b: Light/dark mode using light-dark()
Light-dark means two different color schemes for the page. In this case, we might have a light or white background with black or dark text. Dark mode would be the reverse. There may be personal preference involved for a color scheme, but it’s also critical for accessibility where users may be able to see or read better in different modes.
Let’s set up our colors which will toggle from one mode to another with the CSS function light-dark(). We can test this using operating system settings as we have not yet applied user switching in the browser.
6c: Theme switcher with radio buttons
Remember that CSS has only one event, the hover state. There is no click event in CSS. There are, however, tricks we can play using the :checked pseudoclass in a CSS selector. This would indicate that when a checkbox or radio button is checked, apply certain styling. Unfortunately, there is no :unchecked pseudoclass or a way for applying CSS styling when a box is unchecked. Therefore, two radio buttons, one assigned to each color theme, will apply our different color themes depending on which is selected.
6d: Theme switcher with a switch
I know you really want a switch for toggling between themes rather than those ugly radio buttons. Fortunately, Scott O'Hara has come up with a way of styling two radio buttons into a switch -- and it's accessible to boot! We'll combine his code with the CSS we've already written.