Theming your web application used to be very nasty, you had to use javascript to do the heavy lifting of changing the visuals of the elements or to create multiple representations for each element based on the current theme. So much clutter just for theming.
Nowadays, it is so much easier and cleaner to achieve thanks to CSS Variables.
What are CSS Variables?
Actually they are much like any other variables you know from other languages. You define them as part of the CSS of an element and then they can be used in the CSS of the element itself and its children nodes.
You define a variable as follows:
selector {
--my-variable: value;
}
The value can be any CSS value you would like (even another variable).
Using a variable is as easy as defining:
selector {
color: var(--my-variable);
}
For a live example take a look below:
How to easily theme with CSS Variables?
First of all, we have to understand what are the variables we need for our theme. For simplicity sake, let's say that we have only two variables for our theme, the primary color and secondary color. In a real use case there will be much more variables probably (for example shadow, font, etc).
Second, let's define the variables for each theme (my personal preference is to define at the html
element level but feel free to use wherever you want). We will separate the themes by classes. Again let's say that we have only two themes, default and blue theme.
html {
--my-primary: red;
--my-secondary: blue;
}
html.blue {
--my-primary: blue;
--my-secondary: red;
}
Let's use these variables to style our element:
.child {
color: var(--my-primary);
background: var(--my-secondary);
}
Now if we toggle the blue
class in the html
element our child
element will change its visuals with no further effort. Very clean and intuitive code and if we would like to add a new class it is as easy as adding another class to html
. For a full working example:
Let the theming begin!
Top comments (3)
This website now uses CSS Variables for theming, it's still in beta but feel free to have a look and contribute if you like 😀
New Feature: Personal Configuration (sans serif fonts/night mode beta)
Ben Halpern
[WIP] Theme-able CSS Variables #1377
I thought we ought to have a place where we keep a note of the current CSS Variables and also propose different variables that should be included.
Currently included:
--theme-background
#f9f9fa
--theme-top-bar-background
#fdf9f3
Pull request pending:
--theme-top-bar-color
#0a0a0a
--theme-top-bar-search-background
#e8e7e7
--theme-top-bar-search-color
#0a0a0a
Proposed:
--theme-color
#0a0a0a
--theme-container-background
#ffffff
--theme-container-color
#0a0a0a
I think the best thing to do is leave a comment below of further proposals and I will update the main post.
Also feel free to do pull requests to help roll these out.
Thanks for sharing, I will take a look :)
Also works in IE11 with this polyfill:
github.com/nuxodin/ie11CustomPrope...
Demo:
jsbin.com/dapunoquyo/1/edit?html,c...