open menu

CSS Variables in JS

Do you know how to use CSS variable? Let's learn that in this blog

I'm sure you know and may have used variables in CSS, which are pretty helpful. But do you know that you can also target the CSS variables in JavaScript?

In this blog, you an idea of what awesome things you can do by using CSS variables in JavaScript. We will make a simple project with a light/dark mode switcher using CSS variables.

Before I jump into the project, here's key takeaway from this blog post.

You define your variables in CSS

:root {
  --primary: #d35400;
  --font_size: 40px;

You target them in JavaScript like this:

const docElement = document.documentElement

someBtn.addEventListener('click', () => {'--primary', '#ecf0f1')'--font_size', '30px')

Alright, let's make a simple project and see how can we utilize this feature.

Consider the following HTML code block

<h1>This is heading</h1>
<button class="btn">Change Mode</button>

Consider the following CSS classes

:root {
  --primary: #d35400;
  --background: #ecf0f1;
  --accent: #bdc3c7;

We set the variables in :root pseudo-class, which will help us to easily switch between light and dark mode.

Lastly, we add the following CSS for some styling

body {
  background: var(--background);
  color: var(--primary);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  font-size: 40px;

button {
  background: var(--accent);
  font-size: 40px;
  padding: 5px 20px;
  border: 1px solid;

This will look give us the following result: Light Mode

Make an index.js file and write the following code:

const docElement = document.documentElement
const btn = document.querySelector('.btn')

let isDarkMode = false
btn.addEventListener('click', () => {
  if (isDarkMode) {'--primary', '#d35400')'--background', '#ecf0f1')'--accent', '#bdc3c7')
    isDarkMode = false
  } else {'--primary', '#e67e22')'--background', '#34495e')'--accent', '#95a5a6')
    isDarkMode = true

Congrats! The project is ready. This will let you switch between light mode and dark mode by tapping the button. Dark Mode

The first line in the javascript file sets the docElement to the root element of the page. Then, using the button we have in html, we simply make a click event listener that listens to the button click.

If the current mode is light, we change the variable values to dark mode's values and vice versa.

That's it! It's this much simple to set up light mode and dark mode using CSS Variables in JS.