I recently added a fairly straightforward color scheme (theme) switcher to my personal website. You can toggle this simple color switcher in the footer of the site to see it in action. In case anyone else had the desire to add such functionality to their own sites/projects, I figured I’d write up a quick post explaining how to do so. Let’s get into it.
First we need to include the “buttons” that will trigger the theme to switch based on which one is selected. (Note: you could always render these as
options in a
select element if you preferred that method)
That’s it! Don’t worry too much about the
html element, like so:
Next we need to style both the
color-select buttons, along with the custom color schemes that will alter the entire website. We will start with the color schemes.
For these themes to swap seamlessly between each other, we will be setting our altering color sets as CSS variables:
Finally, we style the user-facing color swatches:
We need to have each color swatch button trigger it’s corresponding theme and swap out the
theme-default class that we have originally attached to the main
html element. We also need to store what the user has selected into
localStorage, so their choice persists when reloading or navigating to other pages.
And that’s it! Now it just depends on how custom you want each individual theme style to be. The possibilities are endless!
You could improve this concept even further hiding the
← Back to all articles
If you would like help support this blog, please consider donating to help keep articles ad-free.
This site is an honorary member of the 1MB Club.
No third-party advertising or data collection - More about privacy.
Built with Jekyll & hosted on Netlify.
Maintained with ♥ for the web.
This page is valid HTML