You are currently viewing CSS: Variables – Using Custom Properties

CSS: Variables – Using Custom Properties

CSS variables, also known as custom properties, are a powerful feature that allows developers to define reusable values throughout a stylesheet. These variables can be used to store colors, fonts, sizes, or any other CSS value, making it easier to maintain and update styles. By using CSS variables, you can create a more modular and scalable stylesheet, where changes to a single variable can propagate throughout the entire document.

The importance of CSS variables lies in their ability to simplify the management of large stylesheets. Instead of repeating the same values in multiple places, you can define them once and reference them wherever needed. This not only reduces redundancy but also makes it easier to implement design changes consistently across a website. In this article, we will explore the syntax and usage of CSS variables, and how to override them.

Basic Syntax of CSS Variables

CSS variables are defined using the -- prefix and are typically declared within a :root selector for global scope. They are then referenced using the var() function.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	
    <style>
	
        :root {
            --main-bg-color: lightblue;
            --main-text-color: darkblue;
        }

        body {
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
        }
		
    </style>
	
    <title>Basic Syntax of CSS Variables</title>
	
</head>
<body>

    <h1>Welcome to My Website</h1>
    <p>This is an example of using CSS variables.</p>
	
</body>
</html>

In this example, two CSS variables, --main-bg-color and --main-text-color, are declared within the :root selector, making them available throughout the document. These variables are then used in the body selector to set the background and text colors. The var() function is used to reference the variables, demonstrating the basic syntax of defining and using CSS variables.

Using CSS Variables

CSS variables can be used anywhere a regular CSS value can be used, such as in color, size, or any other CSS property. This allows for consistent and reusable values across different elements and styles.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	
    <style>
	
        :root {
            --main-bg-color: lightblue;
            --main-text-color: darkblue;
            --padding: 10px;
            --border-radius: 5px;
        }

        .box {
            background-color: var(--main-bg-color);
            color: var(--main-text-color);
            padding: var(--padding);
            border-radius: var(--border-radius);
        }
		
    </style>
	
    <title>Using CSS Variables</title>
	
</head>
<body>

    <div class="box">
        <h1>CSS Variables in Action</h1>
        <p>This box uses CSS variables for its styles.</p>
    </div>
	
</body>
</html>

In this example, additional CSS variables --padding and --border-radius are defined. These variables are then used in the .box class to set the padding and border radius. This demonstrates how CSS variables can be used to create consistent and reusable styles across different elements.

Overriding CSS Variables

CSS variables can be overridden in more specific contexts, such as within a specific element or class. This allows for greater flexibility and customization.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	
    <style>
	
        :root {
            --main-bg-color: lightblue;
            --main-text-color: darkblue;
        }

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

        .override {
            --main-bg-color: lightcoral;
        }

        .override-box {
            background-color: var(--main-bg-color);
        }
		
    </style>
	
    <title>Overriding CSS Variables</title>
	
</head>
<body>

    <div>
        <p>This text uses the global background color variable.</p>
    </div>
	
    <div class="override override-box">
        <p>This text overrides the background color variable.</p>
    </div>
	
</body>
</html>

In this example, the .override class redefines the --main-bg-color variable to light coral. The .override-box class then uses this overridden variable to set its background color. This demonstrates how CSS variables can be overridden in specific contexts, allowing for customized styles within different sections of a page.

Media Queries with CSS Variables

CSS variables can be used within media queries to apply different values based on screen size or other conditions. This enables responsive design with consistent variable usage.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	
    <style>
	
        :root {
            --main-bg-color: lightblue;
            --main-text-color: darkblue;
        }

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

        @media (max-width: 600px) {
		
            :root {
                --main-bg-color: lightcoral;
                --main-text-color: darkred;
            }
			
        }
		
    </style>
	
    <title>Media Queries with CSS Variables</title>
	
</head>
<body>

    <h1>Responsive Design with CSS Variables</h1>
	
    <p>Resize the browser window to see the background and text colors change based on the screen size.</p>
	
</body>
</html>

In this example, the default values for the --main-bg-color and --main-text-color variables are set to light blue and dark blue, respectively. Within the media query, when the screen width is 600 pixels or less, the values of these variables are overridden to light coral and dark red. This demonstrates how CSS variables can be used within media queries to create responsive designs.

JavaScript and CSS Variables

CSS variables can also be manipulated using JavaScript, allowing for dynamic updates to styles based on user interactions or other events.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	
    <style>
	
        :root {
            --main-bg-color: lightblue;
        }

        body {
            background-color: var(--main-bg-color);
            transition: background-color 0.5s ease;
        }

        button {
            padding: 10px 20px;
            font-size: 16px;
        }
		
    </style>
	
    <title>JavaScript and CSS Variables</title>
	
</head>
<body>

    <button onclick="changeColor()">Change Background Color</button>

    <script>
	
        function changeColor() {
            const root = document.documentElement;
            root.style.setProperty('--main-bg-color', 'lightgreen');
        }
		
    </script>
	
</body>
</html>

In this example, a button is provided that, when clicked, changes the background color of the body. The JavaScript function changeColor() accesses the :root element and updates the --main-bg-color variable to light green. This demonstrates how CSS variables can be dynamically manipulated using JavaScript to update styles in response to user interactions.

Conclusion

In this article, we explored the use of CSS variables, also known as custom properties. We discussed their syntax and declaration, how to use and override them, incorporating them within media queries, and manipulating them with JavaScript.

The examples and concepts covered in this article provide a solid foundation for working with CSS variables. However, the possibilities are endless. I encourage you to experiment further and explore how different variable techniques can enhance your web designs.

Additional Resources for Learning About CSS Variables

To continue your journey with CSS variables, here are some additional resources that will help you expand your knowledge and skills:

  • MDN Web Docs – CSS Variables: The official MDN documentation provides comprehensive information on CSS variables. MDN CSS Variables
  • CSS-Tricks: CSS-Tricks offers a variety of articles and tutorials on CSS variables and related topics. CSS-Tricks CSS Variables

By leveraging these resources and continuously practicing, you’ll become proficient in using CSS variables and be well on your way to creating impressive and functional web designs.

Leave a Reply