0
0
CSSmarkup~5 mins

Why CSS variables are used

Choose your learning style9 modes available
Introduction

CSS variables help you reuse colors, sizes, or other values easily. They make changing styles faster and keep your code neat.

When you want to use the same color in many places and might change it later.
When you want to keep font sizes consistent across your website.
When you want to create themes that can switch colors quickly.
When you want to avoid repeating the same values in your CSS.
When you want to make your CSS easier to read and update.
Syntax
CSS
:root {
  --main-color: #3498db;
}

.element {
  color: var(--main-color);
}
CSS variables start with two dashes, like --main-color.
Use var(--variable-name) to get the value of a variable.
Examples
This sets a button's background color using a CSS variable.
CSS
:root {
  --primary-color: #ff6347;
}

button {
  background-color: var(--primary-color);
}
This uses a variable for font size to keep text consistent.
CSS
:root {
  --font-size: 1.2rem;
}

p {
  font-size: var(--font-size);
}
This applies the same padding value to a container using a variable.
CSS
:root {
  --padding: 1rem;
}

.container {
  padding: var(--padding);
}
Sample Program

This example shows how CSS variables control background color, text color, and padding. Changing the variable values updates the whole page style easily.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>CSS Variables Example</title>
  <style>
    :root {
      --main-bg-color: #282c34;
      --main-text-color: #61dafb;
      --padding-size: 1.5rem;
    }

    body {
      background-color: var(--main-bg-color);
      color: var(--main-text-color);
      padding: var(--padding-size);
      font-family: Arial, sans-serif;
    }

    h1 {
      font-size: 2rem;
    }

    p {
      font-size: 1rem;
    }
  </style>
</head>
<body>
  <h1>Welcome to CSS Variables</h1>
  <p>Using variables makes styling easier and faster.</p>
</body>
</html>
OutputSuccess
Important Notes

CSS variables can be changed with JavaScript for dynamic styling.

Variables inside :root are global and can be used anywhere in your CSS.

Using variables reduces mistakes and saves time when updating styles.

Summary

CSS variables store reusable values like colors and sizes.

They make your CSS easier to maintain and update.

Using variables helps keep your website consistent and neat.