Breno Baptista

Reusing Entities With CSS Custom Properties

Table of Contents

Reusing entities

To declare a CSS variable you will have to add a double dash before the name of that var:

:root {
  --green-color: #1B4D3E;
}

To use the value of the CSS variable, we can use the var function:

.green-component {
  background-color: var(--green-color);
}

Adding Dark Mode

Create a file called _variables.scss, so you can set up all CSS variables. Then import that file into your main styles.scss using Sass partials.

:root {
  --font-primary: 'Montserrat', sans-serif;
  --font-secondary: 'Roboto', sans-serif;
  --wide-spacing: 0.25px;
  --bg-primary: #f7fafc;
  --bg-secondary: #ffffff;
  --border-color: #d4e5f9;
  --text-primary: #000000;
  --text-secondary: #00000080;
  --focus: #000000;
  --shadow: rgba(0, 0, 0, 0.4);
  --invert-color: none;
}

.dark {
  --bg-primary: #000000;
  --bg-secondary: #111014;
  --border-color: #2a3139;
  --text-primary: #ffffff;
  --text-secondary: #999999;
  --focus: #ffffff;
  --invert-color: grayscale(1) invert(1);
}

Then, in your JavaScript logic, you can add the class dark to the html tag. In React you can do something similar to this:

// if theme is 'dark' then class is 'dark', if not then class is empty
useEffect(() => {
  document.getElementsByTagName('html')[0].classList.toggle('dark', theme === 'dark')
}, [theme])

Using Inspector

To check CSS variables, open the Inspector for your web browser (right-click a page and select Inspect) and scroll down until you see something like this:

CSS variables

You can change these values on the browser to test different styles more easily.


Low-poly portrait of Breno Baptista

Breno Baptista is a software engineer who likes to explore new things every day. He is interested in Linux, open-source software, digital privacy and front-end development.