Changing color themes in CSS [Simple method]
I will show the most simple method to implement color schemes for your website with good browser version compatibility. You can use it just to implement the hyped "battery saving night color palette", or to add multiple themes for the different target audiences.
1) Create a separate file with a name, let's say themes.css
and define variables in it:
:root { | |
--bg-color: #E9EEF0; | |
--font-color: #FFFFFF; | |
--hover-color: #434343; | |
} | |
[theme="dark"] { | |
--bg-color: #262C38; | |
--font-color: #3A4456; | |
--hover-color: #D3D5DC; | |
} |
Here:
:root
is the main color scheme (used as a fallback if no theme selected)theme
– the name of the variable that holds the name of the color schemedark
– actually, the name of a color scheme. You any name you like, but remember it should be without spaces. For example ⛔WRONG:black color scheme
, ✅CORRECT:black-color-scheme
Everything placed between {}
– is a set of variables containing colors. The variable names should be the same for both schemas. If the variable missing in the theme, the value from :root
will be used.
2) Link this file to HTML e.g. with link tag in head:
<link rel="stylesheet" href="themes.css">
3) Use variables to your other CSS files:
.cool-div { | |
background-color: var(--bg-color); | |
color: var(--font-color); | |
&:hover { | |
background-color: var(--hover-color); | |
} | |
} |
4) Create onclick
handler for element (button, for example) which will switch the current theme, and make it run the following code:
function switchCssTheme() { | |
var htmlElement = document.documentElement; | |
var theme = theme !== 'dark' ? 'dark': ''; // just example | |
htmlElement.setAttribute('theme', theme); | |
} |
Now click on the button and the theme will be changed from the default described in :root
to dark
and variables from the dark theme will be used.
You can also store the theme
variable to localStorage or post to backend users profile to load preferred them next time when user will visit your website.
For your information: the compatibility of this method is 94% according to the caniuse which is definitely a great deal, assuming the fact it will race more and more with years.
Hope you enjoyed this simple quick tutorial and soon will start implementing the best nighttime color palette ever for your website.