0
0
CSSmarkup~5 mins

Declaring variables in CSS

Choose your learning style9 modes available
Introduction

CSS variables let you store values you want to reuse. This makes changing styles easier and faster.

You want to use the same color in many places and change it once to update all.
You want consistent spacing or font sizes across your website.
You want to create themes that can switch colors easily.
You want to keep your CSS clean and avoid repeating the same values.
You want to make your design responsive by changing variables in media queries.
Syntax
CSS
:root {
  --variable-name: value;
}

.element {
  property: var(--variable-name);
}

Variables start with two dashes --.

Use var(--variable-name) to access the variable's value.

Examples
This sets a blue color variable and uses it for all <h1> headings.
CSS
:root {
  --main-color: #3498db;
}

h1 {
  color: var(--main-color);
}
This stores padding size in a variable and applies it to a container.
CSS
:root {
  --padding-size: 1.5rem;
}

.container {
  padding: var(--padding-size);
}
This saves a font family list in a variable and uses it for the whole page.
CSS
:root {
  --font-stack: 'Arial', sans-serif;
}

body {
  font-family: var(--font-stack);
}
Sample Program

This example shows how to declare CSS variables for color, padding, and font size. The variables are used in the body and button styles. The media query changes padding and font size on small screens, showing how variables help with responsive design.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>CSS Variables Example</title>
  <style>
    :root {
      --primary-color: #e67e22;
      --padding: 2rem;
      --font-size: 1.25rem;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: var(--primary-color);
      padding: var(--padding);
      font-size: var(--font-size);
      color: white;
    }

    button {
      background-color: white;
      color: var(--primary-color);
      border: none;
      padding: 0.5rem 1rem;
      font-size: var(--font-size);
      cursor: pointer;
      border-radius: 0.25rem;
    }

    button:hover {
      background-color: #d35400;
      color: white;
    }

    @media (max-width: 600px) {
      :root {
        --padding: 1rem;
        --font-size: 1rem;
      }
    }
  </style>
</head>
<body>
  <h1>Welcome to CSS Variables</h1>
  <p>This page uses variables for colors, padding, and font size.</p>
  <button>Click Me</button>
</body>
</html>
OutputSuccess
Important Notes

CSS variables are case-sensitive and must start with --.

You can override variables inside selectors or media queries for flexible designs.

Variables help keep your CSS DRY (Don't Repeat Yourself).

Summary

Declare CSS variables inside :root for global use.

Use var(--variable-name) to apply the variable's value.

Variables make styling easier to maintain and update.