Create a Theme Switcher With CSS Variables

2022-06-02

CSS variables (also known as custom properties) is a relatively new CSS specification which is now supported by all modern browsers . CSS variables allow developers to declare and update values in CSS at runtime in the browser, previously this was only possible using a preprocessor such as SASS or LESS. Since CSS variables can be updated in the browser with javascript they can be used to create a color theme switcher or to update any style property in a website.

Writing CSS variables

All CSS variables are defined in theme.css. All values are determined based on attributes of the :root element. This way we can switch themes by setting different values for these attributes. For example we could use document.documentElement.setAttribute('color-mode', 'dark'); to change the color theme to dark.

:root {
--sans: -apple-system, blinkmacsystemfont, 'Segoe UI', roboto, oxygen, ubuntu,
cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
--serif: Constantia, 'Lucida Bright', Lucidabright, 'Lucida Serif', Lucida,
'DejaVu Serif', 'Bitstream Vera Serif', 'Liberation Serif', Georgia, serif;
--bg0: #f8f9fa;
--bg1: #e9ecef;
--bg2: #dee2e6;
--bg3: #ced4da;
--txt0: #000;
--txt1: #212529;
--txt2: #343a40;
--txt3: #495057;
--highlight: #0d6efd;
}
:root[font-mode='sans'] {
--text: var(--sans);
}
:root[font-mode='serif'] {
--text: var(--serif);
}
:root[color-mode='light'] {
--bg0: #f8f9fa;
--bg1: #e9ecef;
--bg2: #dee2e6;
--bg3: #ced4da;
--txt0: #000;
--txt1: #212529;
--txt2: #343a40;
--txt3: #495057;
--highlight: #0d6efd;
}
:root[color-mode='solarized'] {
--bg0: #fdf6e3;
--bg1: #eee8d5;
--bg2: #ddd6c1;
--bg3: #d1cbb8;
--buttonbg: #b58900;
--txt0: #000;
--txt1: #212529;
--txt2: #343a40;
--txt3: #495057;
--highlight: #cb4b16;
}
:root[color-mode='dark'] {
--bg0: #212529;
--bg1: #343a40;
--bg2: #495057;
--bg3: #6c757d;
--txt0: #fff;
--txt1: #f8f9fa;
--txt2: #e9ecef;
--txt3: #dee2e6;
--highlight: #0d6efd;
}
:root[color-mode='cobalt'] {
--bg0: #15232d;
--bg1: #122738;
--bg2: #163042;
--bg3: #193549;
--buttonbg: #5d37f0;
--txt0: #ffffff;
--txt1: #f8f9fa;
--txt2: #e9ecef;
--txt3: #dee2e6;
--highlight: #ffc600;
}