DEV Community

VICTOR OMONDI
VICTOR OMONDI

Posted on

CSS Variables for beginners

CSS Variables for beginners

:root {
    --primary-color: #f03d06;
  }

  .main-header {
    color: var(--primary-color);
  }
  .main-footer {
    background-color: var(--primary-color);
  }
Enter fullscreen mode Exit fullscreen mode

To declare a CSS variable we will have to add a double dash before the name of that variable.

To access a CSS variable try:
var(--your-variable-name)

CSS variables declared in :root will make sure that all selectors can gain access to them

Top comments (1)

Collapse
 
alexandersstudi profile image
Alexander

Grasping the basics of custom properties completely changes how you structure stylesheets. One trick worth adding for beginners is using fallback parameters directly inside the function, like var(. primary-color, #333). If the root token is missing or accidentally overwritten, the browser gracefully uses the fallback rather than breaking the UI. Because they respect the DOM cascade, they offer runtime flexibility that traditional preprocessor variables simply cannot match.