Understanding CSS Variables [With Examples]

CSS variables, also known as custom properties, are used to store reusable values in a CSS document. Defined with two dashes (–), these variables enhance code efficiency and readability by allowing centralized updates of values such as colors and sizes. This article explores the syntax, usage, and benefits of CSS, illustrating their scope through practical examples to help you streamline your web design process.

Syntax:

Parameters:

The variable var() accepts two parameters which are listed below:

  • –custom-name: It is a required parameter that accepts the custom property name starting with two dashes.
  • value: It is an optional parameter. It accepts a fallback value which is used when a custom property is invalid.

 

Benefits of Using CSS Variables

  1. Maintainability: By defining values in one place, you can easily update your styles without having to find and replace multiple instances in your CSS.
  2. Reusability: Use the same variable in multiple places to ensure consistency.
  3. Dynamic Styling: CSS Variables can be updated dynamically with JavaScript.

CSS Variables Examples

We will understand the above concepts through the examples.

<!DOCTYPE html>
<html>
<head>
    <title>CSS Variables</title>
    <style>

    :root {
        --bg-color: rgb(0, 0, 0);
        --txt-color: white;
        --a-border: 3px solid red;
    }
    /* var() function used here */
    
    body {
        background-color: var(--bg-color);
    }
    
    h1 {
        color: var(--txt-color);
        border: var(--a-border);
    }
    
    div {
        color: var(--txt-color);
    }
    </style>
</head>

<body>
<div class="container">
    <h1>CSS Variables</h1>
    <div> CSS variables, also known as custom properties, are used to store reusable values in a CSS document. Defined with two dashes (–), these variables enhance code efficiency and readability by allowing centralized updates of values such as colors and sizes. This article explores the syntax, usage, and benefits of CSS variables, illustrating their scope through practical examples to help you streamline your web design process. </div>
  </div>
</body>
</html>

Read Also:-

Understanding PHP 8 Named Arguments

Array Destructuring in ES6: Enhance Your JavaScript Code

Also Visit:-

https://inimisttech.com/

Leave a Reply