{
  "$type": "site.standard.document",
  "path": "/styling-with-css-vars/",
  "publishedAt": "2019-02-16T19:45:00.000Z",
  "site": "at://did:plc:6gssgguzeecdttuw4gpdshg2/site.standard.publication/self",
  "tags": [
    "blog",
    "gatsby",
    "css",
    "coding"
  ],
  "textContent": "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.\n\nWhat 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.\n\nQuick note: This post is best viewed in a modern browser that supports css variables.\n\nDefining a new CSS variable looks like this:\n\n[Code block]\n\nThen when you want to use that value:\n\n[Code block]\n\nYou can also provide a fallback value in the case the variable is not defined:\n\n[Code block]\n\nRight 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.\n\nUpdating 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:\n\n[Code block]\n\nThen 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:\n\n[Code block]\n\nNow 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:\n\n[Interactive demo]\n\nYou 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.\n\nthemeChanger.js:\n\nThis component handles updating the DOM and state when our CSS variables change.\n\n[Code block]\n\nthemeButton.js:\n\nA button element that loads a pre-made theme.\n\n[Code block]\n\ncolorEditor.js:\n\nOpens a react-color color picker and handles updating the color.\n\n[Code block]\n\nthemes.js\n\nThe list of pre-made themes and variables used for this sites theme.\n\n[Code block]\n\nThere 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!\n\nRead the original post with all embeds and interactive content at https://rants.broonix.ca/styling-with-css-vars/",
  "title": "Styling with CSS variables"
}