Styling with CSS variables
Broonix
February 16, 2019
This weekend I've messing around with CSS variables. I figured it might be fun to see if I could build a way to style this site using only CSS variables.
What are CSS variables? Well after all these years we finally have a way to define a value and reuse it in other places. Sure SASS and LESS gave us access to something similar, but compile down to CSS. Variables are dynamic in CSS so we can even be redefine at run time. Their syntax is nice an simple.
Quick note: This post is best viewed in a modern browser that supports css variables.
Defining a new CSS variable looks like this:
[Code block]
Then when you want to use that value:
[Code block]
You can also provide a fallback value in the case the variable is not defined:
[Code block]
Right now this blog is a mix of pair CSS files and Emotion for component styling. The CSS files are reset.css which is a generic CSS reset file to ensure a standard look and feel between browsers and theme.css which styles things like links, code blocks and inline code.
Updating everything to use CSS variables was ridiculously simple. I worked out the list of all colors used on my blog and their function. I defined all the new values I need as part of the :root element of my document in theme.css:
[Code block]
Then all I needed to do was update any usages of these colors in my CSS files and Emotion styled components. Here's what the Tag component now looks like:
[Code block]
Now to the viewer this blog it more or less looks the exact same as before, but one of the coolest things about CSS variables is that you can redefine them at runtime. Given my new blog format I can now create much more interactive demos. Something like this:
[Interactive demo]
You can load any theme and browse around my blog. The theme will remain active until you reload the page. If you are wondering how my ThemeChanger control works here's the source code.
themeChanger.js:
This component handles updating the DOM and state when our CSS variables change.
[Code block]
themeButton.js:
A button element that loads a pre-made theme.
[Code block]
colorEditor.js:
Opens a react-color color picker and handles updating the color.
[Code block]
themes.js
The list of pre-made themes and variables used for this sites theme.
[Code block]
There you have it, my blog can now be easily themed via CSS variables. If you have any questions or comments let me know below. Happy coding!
Read the original post with all embeds and interactive content at https://rants.broonix.ca/styling-with-css-vars/
Discussion in the ATmosphere