The Front-End
CSS
Variables

CSS Variables

CSS variables, also known as custom properties, provide a way to store and reuse values in your stylesheets. Here's an in-depth guide with code snippets and examples:

  1. Declaring CSS Variables
  2. Using CSS Variables
  3. Dynamic Value Changes
  4. Fallback Values
  5. Using Variables in Media Queries
  6. CSS Variables in Keyframe Animations
  7. Example

Declaring CSS Variables

Declare a variable using the -- prefix.

:root {
  --main-color: #3498db;
  --bg-color: #ecf0f1;
}

Using CSS Variables

Access and use variables throughout your stylesheet.

body {
  background-color: var(--bg-color);
}
 
.header {
  color: var(--main-color);
}

Dynamic Value Changes

Change variable values dynamically with JavaScript.

:root {
  --main-color: #3498db;
}
 
body {
  background-color: var(--main-color);
}
 
.dark-mode body {
  --main-color: #2c3e50;
}

Fallback Values

Provide fallback values for browsers that do not support CSS variables.

:root {
  --main-color: #3498db;
}
 
body {
  background-color: var(--main-color, #3498db);
}

Using Variables in Media Queries

Make your stylesheets more maintainable by using variables in media queries.

:root {
  --main-color: #3498db;
}
 
@media screen and (min-width: 768px) {
  body {
    font-size: 18px;
    color: var(--main-color);
  }
}

CSS Variables in Keyframe Animations

Utilize variables in keyframe animations for consistent styling.

:root {
  --animation-duration: 2s;
}
 
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
 
.fade-in {
  animation: fadeIn var(--animation-duration);
}

Example

Dynamic Theming with CSS Variables

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dynamic Theming Example</title>
  <style>
    :root {
      --main-color: #3498db;
      --bg-color: #ecf0f1;
    }
 
    body {
      background-color: var(--bg-color);
      color: var(--main-color);
      transition: background-color 0.3s ease;
    }
 
    .toggle-button {
      padding: 10px;
      background-color: var(--main-color);
      color: white;
      border: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>Dynamic Theming Example</h1>
  <button class="toggle-button" onclick="toggleTheme()">Toggle Theme</button>
 
  <script>
    function toggleTheme() {
      document.documentElement.classList.toggle('dark-mode');
    }
  </script>
</body>
</html>