Switch to Dark Mode using Only CSS variables

Switch to Dark Mode using Only CSS variables

Anoop Jadhav's photo
Anoop Jadhav
·Sep 19, 2022·

2 min read

The easiest way to implement dark mode in your website or portfolio apps is by using CSS variables. In my portfolio app I relied on CSS variables to switch between dark & light mode.

I implemented this using SCSS as a commonStyle library for my personal portfolio. But a simplified version in CSS would look as below -


body {
  /* grey values */
  --grey1: #212122; /* darkest */
  --grey2: #333333;
  --grey3: #828282;
  --grey4: #bdbdbd;
  --grey5: #e0e0e0;
  --grey6: #f2f2f2;
  --grey7: white; /* lightest */

  --red: #eb5757;

  /* banner colors */
  --orange: #f2994a;
  --yellow: #f2c94c;
  --green: #27ae60;

  /* primary & accent color */
  --primary-color: var(--red);
  --accent-color: var(--orange);

  /* use variables to set colors as follows - */
  background: var(--grey7);
  color: var(--grey1);

/* reverse the color values for darkmode*/
body.darkmode {
  --grey1: white; /* lightest */
  --grey2: #f2f2f2; 
  --grey3: #e0e0e0;
  --grey4: #bdbdbd;
  --grey5: #828282;
  --grey6: #333333;
  --grey7: #212122; /* darkest */

The color values will switch as soon as you append darkmode class to the body element.

here is the VS code + color highlight plugin version of the same code - Screenshot 2022-09-19 at 2.46.26 PM.png

The only pending part now is to append the darkmode class to the body when you click on the darkmode toggle button. In JS you can use -

function toggleButtonHandler() {

Thanks !

Did you find this article valuable?

Support Anoop Jadhav by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this