2

Theming with CSS variables.

 2 years ago
source link: https://dev.to/enesskilic/theming-with-css-variables-cp8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Theming with CSS variables.

Theming with CSS variables.

Aug 5

・1 min read

In this article, I will talk about how to make theming with CSS variables. With this example, we will see again the importance of using variables.

Step 1: Define your variables.

/* Define your variables to the root. */
:root {
  --black: #181818;
  --white: #f5f7f7;
  --fade:  150ms;
}

/*  
The variables of the tag with the data-theme="light" attribute.
We will then apply this property to the HTML tag with javascript,
but you can define it manually.
*/
[data-theme="light"]{
  --color-text: var(--black);
  --color-background: var(--white);
}

/* Change variables for dark theme. */
[data-theme="dark"]{
  --color-text: var(--white);
  --color-background: var(--black);
}

/* And apply styles to document root element. */
html {
  color: var(--color-text);
  background-color: var(--color-background);

  /* for smooth color transitions. */
  transition: var(--fade) color, var(--fade) background-color;
}

Enter fullscreen modeExit fullscreen mode

Step 2: Add functionality with javascript.

// Call theme value from browsers local storage.
var theme = localStorage.getItem("theme");
// Root element of the document.
const _root = document.documentElement;

// Check if local storage has no theme value, define the initial value.
!theme && localStorage.setItem("theme", "light");

// Update theme value.
theme = localStorage.getItem("theme");

// Apply theme value to document root element.
_root.setAttribute("data-theme", theme);

// Function for change theme.
// You can define this function to the a button or call this any way.
function changeTheme() {
  theme === "light"
    ? localStorage.setItem("theme", "dark")
    : localStorage.setItem("theme", "light");

  // Update theme value
  theme = localStorage.getItem("theme");

  // Apply theme to document root element
  _root.setAttribute("data-theme", theme);
}
Enter fullscreen modeExit fullscreen mode

Result


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK