CSS Variables: The Key to More Flexible Styling

Why?

When application become larger, repeated coding become challenging. Also when we need to change some color or size which is same all over the code, in conventional way we need to edit all the place of that value..

CSS variable comes with a solution for this. Instead of changing value all the place one by one. we can declare a variable and then use this. So we will just need to change the variable value to change everything that related.

How?

Declare css variable

Global Scope: For accessing the variables from anywhere in the CSS. Declare within :root

:root {
  --main-text-color: green; 
  --paragraph-font-size: 22px;
} 

Local Scope: only available within the elements

.our-css-class {
  --main-color: azure; 
  background-color: var(--main-color); 
  border: 2px solid var(--main-color);
}

Apply css variable



<!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-text-color: green; 
      --paragraph-font-size: 22px;
    } 
    
    .our-css-class {
      --main-color: azure; 
      background-color: var(--main-color); 
      border: 2px solid var(--main-color);
    }
  </style>
</head>
<body>
  <h1 style="color: var(--main-text-color);">Hello, CSS Variables!</h1>
  <p style="font-size: var(--paragraph-font-size);">This is an example paragraph.</p>
  
  <div class="our-css-class">
    <p>This div has a background color and border defined using CSS variables within the class.</p>
  </div>
</body>
</html>




Test The Code Here

Published by

mashiurrahman99

Programmer