Css Declaring And Using Css Custom Properties Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of CSS Declaring and Using CSS Custom Properties

CSS Declaring and Using CSS Custom Properties (CSS Variables)

Declaring CSS Custom Properties

CSS Custom Properties are declared within a selector using the -- prefix. Typically, they are declared globally within the :root pseudo-class, which represents the <html> element. However, they can also be declared within other selectors to have a more local scope.

Global Declaration:

:root {
    --primary-color: #4CAF50;
    --secondary-color: #ffeb3b;
    --font-size-large: 2rem;
}

In this example, three CSS Custom Properties (--primary-color, --secondary-color, and --font-size-large) are defined globally. This makes them accessible throughout the entire CSS document.

Local Declaration:

.theme-light {
    --background-color: #ffffff;
    --text-color: #333333;
}

.theme-dark {
    --background-color: #121212;
    --text-color: #e0e0e0;
}

Here, two sets of CSS Custom Properties are declared locally within .theme-light and .theme-dark. These local variables override any globally declared variables with the same name within their respective selectors. This approach is useful for theming where different parts of the UI might require different styling values.

Using CSS Custom Properties

OnceCSS Custom Properties are declared, you can use them within your stylesheets by calling them with the var() function. The var() function takes two arguments. The first is the name of the custom property and the second is an optional fallback value.

Using Global Variables:

body {
    font-family: Arial, sans-serif;
    color: var(--text-color);
}

button {
    background-color: var(--primary-color);
    border: none;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: var(--font-size-large);
    margin: 4px 2px;
    cursor: pointer;
}

In this snippet, the global custom properties --text-color, --primary-color, and --font-size-large are used in various elements like body and button.

Using Local Variables:

.card.light-theme {
    background-color: var(--background-color, #eeeeee);
    color: var(--text-color, #000000);
}

.card.dark-theme {
    background-color: var(--background-color, #303030);
    color: var(--text-color, #ffffff);
}

In this example, the locally declared --background-color and --text-color are used within the .card class for different themes. If these properties are not found in the local scope, the fallback values (#eeeeee and #ffffff) will be applied.

Important Information

  1. Dynamic Nature: CSS Custom Properties are computed at runtime, allowing you to dynamically change their values, even within media queries.

    :root {
        --base-spacing: 16px;
    }
    
    @media (min-width: 800px) {
        :root {
            --base-spacing: 24px;
        }
    }
    

    In this snippet, the spacing value changes from 16px to 24px at larger screens.

  2. Scope Management: Variables declared in :root can be overridden by those declared within child selectors. You can also define default values with the var() function, providing robust styling even if certain properties are missing or overridden.

    .container {
        width: 80%;
        margin-left: auto;
        margin-right: auto;
        padding-left: var(--padding, 1rem);
        padding-right: var(--padding, 1rem);
    }
    
  3. Computation: Custom properties can be used as part of computation within the calc() function, offering flexibility in handling values that need arithmetic operations.

    :root {
        --spacing-unit: 10px;
    }
    
    .gutter {
        margin: calc(2 * var(--spacing-unit)) calc(3 * var(--spacing-unit));
    }
    
  4. Specificity: When it comes to resolving variable values, specificity rules still apply. A higher-specificity selector’s custom property value overrides that of a less-specific selector.

    p {
        color: var(--text-color, blue);
    }
    
    .intro p {
        --text-color: green;
    }
    

    In this case, all <p> tags within .intro use the green color as defined by the more specific rule.

  5. JavaScript Interactivity: CSS Custom Properties can also be accessed and manipulated through JavaScript, allowing for real-time style changes based on user interactions.

    // Accessing a CSS Custom Property
    const rootElement = document.documentElement;
    const primaryColor = getComputedStyle(rootElement).getPropertyValue('--primary-color').trim();
    
    // Updating a CSS Custom Property
    rootElement.style.setProperty('--primary-color', '#FF5733');
    
  6. Limitations in CSS Preprocessors: Unlike preprocessor constants, Custom Properties aren’t computed until runtime. This means they are scoped to the page, not the file or project, and are subject to CSS inheritance. Therefore, CSS variables cannot be used directly in preprocessor conditionals or loops since these occur before runtime.

  7. Polyfilling: Although supported in most modern browsers, CSS Custom Properties were initially not available in all versions. For compatibility reasons, developers sometimes use polyfills to backport this functionality to older browsers.

  8. Performance Considerations: While CSS Custom Properties offer many benefits, they can impact performance in scenarios that involve significant recalculations due to variable changes. It’s advisable to use them judiciously to prevent layout thrashing.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement CSS Declaring and Using CSS Custom Properties

Step by Step Guide: Declaring and Using CSS Custom Properties

1. Understanding CSS Custom Properties

CSS Custom Properties allow you to define values that can be used throughout your stylesheets. Unlike traditional CSS properties, custom properties are not inherited; instead, they are accessible using the var() function within styles.

2. Basic Syntax

  • Declaration: Use the -- prefix to declare a custom property.
  • Usage: Use the var() function to reference a custom property.

Example:

/* Declaration */
:root {
    --primary-color: #3498db;
    --secondary-color: #e74c3c;
}

/* Usage */
body {
    background-color: var(--primary-color);
}

button {
    background-color: var(--secondary-color);
}

3. Setting Up Your Project

Create a simple HTML file and link it to a separate CSS file for better organization.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Custom Properties Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>My Website</h1>
    </header>
    <main>
        <p>Welcome to my website. This text uses a custom color.</p>
        <button class="btn-primary">Primary Button</button>
        <button class="btn-secondary">Secondary Button</button>
    </main>
    <footer>
        <p>&copy; 2023 My Website</p>
    </footer>
</body>
</html>

styles.css

/* Initial Setup */
:root {
    --text-color: #333;
    --primary-color: #3498db;
    --secondary-color: #e74c3c;
    --font-size: 16px;
    --spacing: 20px;
}

body {
    font-family: Arial, sans-serif;
    font-size: var(--font-size);
    margin: 0;
    padding: 0;
    line-height: 1.5;
}

header {
    background-color: var(--primary-color);
    color: var(--text-color);
    padding: var(--spacing);
}

main {
    padding: var(--spacing);
}

main p {
    color: var(--text-color);
}

button {
    padding: var(--spacing);
    border: none;
    cursor: pointer;
    color: white;
    font-size: calc(var(--font-size) * 0.8);
    border-radius: 5px;
}

.btn-primary {
    background-color: var(--primary-color);
}

.btn-secondary {
    background-color: var(--secondary-color);
}

footer {
    background-color: var(--secondary-color);
    color: var(--text-color);
    text-align: center;
    padding: var(--spacing);
}

4. Explanation

  • :root Selector: This is typically used to declare global custom properties. The :root selector corresponds to the root element of the document, which in HTML is the <html> element.

Custom Property Declarations:

  • --text-color: #333;: Sets the base text color.
  • --primary-color: #3498db;: Sets the primary brand color (blue).
  • --secondary-color: #e74c3c;: Sets the secondary brand color (red).
  • --font-size: 16px;: Defines the default font size.
  • --spacing: 20px;: Establishes a spacing value that can be easily adjusted.

Applying Custom Properties:

  • background-color: var(--primary-color);: Uses the primary color in the header and primary button.
  • color: var(--text-color);: Applies the default text color in multiple places.
  • padding: var(--spacing);: Consistent spacing around elements improves readability and aesthetics.
  • font-size: calc(var(--font-size) * 0.8);: Uses a calculated size smaller than the default for button text.

5. Customizing for Different States

You can override custom properties in specific selectors to customize them according to different states or components.

Example:

button:hover {
    background-color: darken(var(--secondary-color), 10%);
}

Note: The darken() function used here is not a built-in CSS function but an illustration. There isn't a darken() function directly available in CSS. Instead, you could use a hexadecimal color manipulation library like SASS/SCSS or write the specific darker color manually.

However, here’s an example with manual overriding:

button:hover {
    background-color: #c0392b; /* Manually set a darker shade */
}

6. Custom Properties in JavaScript

CSS Custom Properties can also be set and manipulated using JavaScript, which provides dynamic styling capabilities.

Example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Custom Properties Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>My Website</h1>
    </header>
    <main>
        <button id="toggle-theme-btn">Toggle Theme</button>
    </main>
    <footer>
        <p>&copy; 2023 My Website</p>
    </footer>
    
    <script src="script.js"></script>
</body>
</html>

styles.css

:root {
    --background-color: white;
    --text-color: #333;
    --primary-color: #3498db;
    --secondary-color: #e74c3c;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
    font-family: Arial, sans-serif;
    font-size: var(--font-size);
    margin: 0;
    padding: 0;
    line-height: 1.5;
}

script.js

document.getElementById("toggle-theme-btn").addEventListener("click", function() {
    document.documentElement.style.setProperty('--background-color', '#2c3e50');
    document.documentElement.style.setProperty('--text-color', '#ecf0f1');
});

7. Explanation of JavaScript Example

  • Event Listener: Adds a click event listener to the button with the ID toggle-theme-btn.
  • document.documentElement.style.setProperty() Method: Changes the value of the --background-color and --text-color custom properties at runtime when the button is clicked.

8. Benefits of Using CSS Custom Properties

  • Reusability: Define once, use many times.
  • Maintainability: Makes your stylesheet easier to understand and modify.
  • Dynamic Styling: Enables more flexibility and interactivity when combined with JavaScript.

9. Conclusion

Understanding and using CSS Custom Properties can greatly enhance the maintainability and scalability of your stylesheets. These properties can be applied globally or scoped to specific elements, and they can even be dynamically adjusted with JavaScript.

Feel free to experiment with different custom properties to see how they can improve your web development workflow!


Top 10 Interview Questions & Answers on CSS Declaring and Using CSS Custom Properties

Top 10 Questions and Answers on CSS Declaring and Using CSS Custom Properties

1. What are CSS Custom Properties?

2. How do you declare a CSS Custom Property?

Answer: CSS Custom Properties are declared within a selector, usually the :root pseudo-class to ensure they are globally available. The syntax is --property-name: value;. For example:

:root {
  --main-bg-color: #f0f0f0;
}

3. How do you use a CSS Custom Property?

Answer: Custom properties are used with the var() function. For instance, to use --main-bg-color defined in the previous question, you would write:

body {
  background-color: var(--main-bg-color);
}

4. What are the benefits of using CSS Custom Properties?

Answer: Using CSS Custom Properties improves code maintainability and readability. They allow for easier theming, consistent values, and can reduce repetitive code. They also make styles more dynamic and adaptable, facilitating easier updates.

5. Can CSS Custom Properties inherit values?

Answer: Yes, CSS Custom Properties are inherited just like regular CSS properties. Their values cascade down through the document. This means you can define a custom property in a parent element and have it used in child elements.

.parent {
  --text-color: blue;
}
.parent .child {
  color: var(--text-color); /* This will be blue */
}

6. How do you provide fallback values when using CSS Custom Properties?

Answer: The var() function allows providing fallback values to use when the custom property is invalid or not present. The syntax is var(--property-name, fallback-value).

body {
  background-color: var(--main-bg-color, #ccc); /* If --main-bg-color is not defined, fallback to #ccc */
}

7. Can you nest custom properties like you can with SCSS or LESS?

Answer: CSS Custom Properties do not support nesting out of the box like SCSS or LESS. However, you can achieve a similar effect by organizing your variables logically and using inheritance.

8. How are custom properties scoped?

Answer: CSS Custom Properties are scoped to the element where they are declared. They are cascaded similarly to other CSS properties. Declaring a custom property on a more specific selector will override a less specific one, just like with regular CSS properties.

9. Can JavaScript interact with CSS Custom Properties?

Answer: Yes, JavaScript can read and modify CSS Custom Properties dynamically.

  • Reading a custom property:
const root = document.documentElement;
const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color');
  • Setting a custom property:
root.style.setProperty('--primary-color', '#3498db');

10. What are some common best practices for using CSS Custom Properties?

Answer: Here are some best practices:

  • Keep variable names meaningful and descriptive.
  • Use :root for global variables but consider scoping to specific components if necessary.
  • Use fallback values in var() functions for resilience.
  • Consider using a naming convention, such as prefixing all custom properties with a project identifier, to avoid conflicts.
  • Document your custom properties, especially when they are used across large projects.

You May Like This Related .NET Topic

Login to post a comment.