dark-mode

Creating a CSS Color Variable for Dark Mode: A Step-by-Step Guide

Not sure where to start when it comes to coding for a dark mode? This blog post will give you all the tips and tricks you need to get started with CSS.

Greetings! Are unsure about how to start your CSS code for implementing a dark mode? I decided to write about it because it’s very probable that even if it isn’t a requirement of the client., maybe at a specific moment, after delivery of the project, your client requires you to add a dark mode and … bum! You notice that you haven’t prepared your code for that.

How to create a CSS color variable to support Dark Mode

To create a CSS colors variable that supports dark mode, you can use CSS custom properties (also known as CSS variables). These variables can be defined in your CSS file and then used throughout your stylesheets to maintain consistency and make it easy to switch between light and dark mode.

Here’s a step-by-step guide on how to create a CSS colors variable for dark mode:

Step 1: Define the CSS variables for both light and dark mode In your CSS file or within a style block in your HTML, define the CSS custom properties for the colors you want to use in both light and dark modes:

:root {
  /* Light mode colors */
  --primary-color: #007bff;
  --secondary-color: #6c757d;
  --text-color: #333;
  --background-color: #fff;

  /* Dark mode colors */
  --primary-color-dark: #61dafb;
  --secondary-color-dark: #adb5bd;
  --text-color-dark: #f0f0f0;
  --background-color-dark: #333;
}

Step 2: Use the CSS variables in your styles Now that you have defined the CSS variables, you can use them throughout your stylesheets:

body {
  color: var(--text-color);
  background-color: var(--background-color);
}

a {
  color: var(--primary-color);
}

/* Additional styles for dark mode */
.dark-mode {
  color: var(--text-color-dark);
  background-color: var(--background-color-dark);
}

.dark-mode a {
  color: var(--primary-color-dark);
}

Step 3: Toggle between light and dark mode To toggle between light and dark mode, you can add a class (e.g., .dark-mode) to the <body> element of your HTML. You can achieve this using JavaScript or by toggling the class manually.

For example, if you are using JavaScript:

// Assuming you have a button with id "dark-mode-toggle"
const toggleButton = document.getElementById('dark-mode-toggle');
const body = document.body;

toggleButton.addEventListener('click', () => {
  body.classList.toggle('dark-mode');
});

Now, when the .dark-mode class is added to the <body> element, all the styles under .dark-mode will be applied, effectively switching the page to dark mode.

That’s it! With these steps, you have created a CSS colors variable that supports dark mode. By toggling the .dark-mode class on the <body> element, you can easily switch between light and dark modes with consistent color styles.