CSS Tutorial

CSS Variables

Introduction

CSS variables let you store and reuse values throughout your stylesheet, enhancing code maintainability and flexibility.

Key Concepts

  • Custom Properties: Variables begin with -- (e.g., --color-background).
  • Variable Declaration: Use the var() function to assign values to variables (e.g., var(--color-background, black)).
  • Variable Usage: Refer to variables using var() in place of values (e.g., background-color: var(--color-background)).

Example

CSS

/* Define reusable variables */
:root {
  --color-primary: #FF0000;
  --color-secondary: #00FF00;
}

/* Use variables in styles */
h1 {
  color: var(--color-primary);
}

p {
  color: var(--color-secondary);
}

Benefits

  • Code Reusability: Variables eliminate the need to repeat values, making code more organized and easier to maintain.
  • Centralized Control: Updates to variables instantly reflect changes throughout the stylesheet, reducing the risk of inconsistencies.
  • Style Customization: Variables allow for easy theme switching and personalization, empowering users to tailor the website's appearance.