⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

CSS Variables

CSS variables (officially called Custom Properties) are a powerful tool for storing and reusing values in CSS. Unlike variables in preprocessor languages like SASS or LESS, CSS variables are part of the DOM and can be changed in real time with JavaScript or used to create dynamic themes (e.g., switching between light and dark theme).

Variables are defined with the -- prefix (e.g., --primary-color) and used with the var() function. They enable centralized management of colors, font sizes, spacing, and other values, which drastically simplifies maintenance of large websites.

EXAMPLE
RESULT

The Example Demonstrates

The example above shows how CSS variables enable dynamic styling of a website. By clicking buttons, you can switch between themes, change colors and spacing in real time – without reloading the page. All changes happen through simple replacement of variable values in the document root.

Theme Switching

  1. Two color sets are defined (light and dark theme).
  2. Switch between themes by clicking a button.
  3. Using the data-theme attribute for switching.

Responsive Design

  1. Adapting font size and spacing on smaller screens.
  2. Changing button layout on smaller screens.
  3. Using @media queries to change variable values.

Dynamic Changes with JavaScript

  1. Changing colors in real time.
  2. Changing spacing between elements.
  3. Displaying current values.

Advantages of Using CSS Variables

  1. Dynamic value changes with JavaScript.
  2. Easier code maintenance.
  3. Better readability.
  4. Support for different themes (light/dark).
  5. Adapting values based on screen size.
Property/Function Example Description
Defining
--variable-name:root { --primary: #3498db; } Defines a variable (starts with two hyphens)
Global:root { --spacing: 10px; } Defining in :root allows access from the entire document
Local.card { --bg: white; } Defining within a specific element (accessible only to it and its children)
Using
var()color: var(--primary); Retrieves the value of a variable
var() with fallbackcolor: var(--primary, red); Retrieves the value; if it does not exist, uses the fallback value (red)
Dynamic Changes
JavaScriptdocument.documentElement.style.setProperty("--primary", "green"); Changing a variable value with JavaScript in real time
Media Queries@media (prefers-color-scheme: dark) { :root { --bg: #333; } } Changing values based on system settings (e.g., Dark Mode)
Hover/Focusa:hover { --color: blue; } Changing values on user interaction