DEV Community

CodePassion
CodePassion

Posted on

Optimizing Web Design with CSS Variables

Declaration and Syntax of CSS Variables
In the CSS rules, we declare variables for the main part of the document, which is often called the :root element. This allows the variable to be used everywhere in the document. However, you can also choose to only focus on certain parts of the document by specifying it in a different selector.

Learn more about how to declare CSS variables

:root {
  --primary-color:#ff0000;
}

Enter fullscreen mode Exit fullscreen mode

Using CSS Variables
CSS variables Once defined, can be applied anywhere in the style sheet using the var() function. (Read More)
For example:

.header {
  color: var(--primary-color);
}

Enter fullscreen mode Exit fullscreen mode

In this example, the text color of elements with the .header class is set to the value stored in the –primary-color variable..

Unveiling the HTML Skeleton

output:

width height slider

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Meta tags and title -->
    <title>CSS Variables Example 2</title>

    <style>
        /* add CSS Code Here */
    </style>
</head>

<body>
    <!-- Container div -->
    <div class="container">
        <!-- Box element -->
        <div class="box"></div>
        <!-- Input range for width -->
        <label for="widthRange">Width:</label>
        <input type="range" id="widthRange" min="50" max="300" value="150">
        <!-- Input range for height -->
        <label for="heightRange">Height:</label>
        <input type="range" id="heightRange" min="50" max="300" value="150">
    </div>

    <!-- JavaScript code -->
    <script>
        //Add JavaScript code here  
    </script>


</body>

</html>
Enter fullscreen mode Exit fullscreen mode

CSS:

:root {
  --box-width: 150px;
  --box-height: 150px;
}
.box {
  width: var(--box-width);
  height: var(--box-height);
  background-color: #3498db;
  margin: 20px auto;
  transition: width 0.5s, height 0.5s;  /* Smooth transition effect */
}

Enter fullscreen mode Exit fullscreen mode

Javascript:

document.getElementById('widthRange').addEventListener('input', function() {
  var widthValue = this.value + 'px';
  document.documentElement.style.setProperty('--box-width', widthValue);
});

document.getElementById('heightRange').addEventListener('input', function() {
  var heightValue = this.value + 'px';
  document.documentElement.style.setProperty('--box-height', heightValue);
});

Enter fullscreen mode Exit fullscreen mode

Conclusion:
Finally, CSS variables offer a new approach to web application development, enabling developers to easily create flexible and adaptive user interfaces. Developers can use CSS variables’ dynamic capabilities to create engaging experiences that respond to user preferences and activities. So, why wait? Step into the world of CSS variables and discover limitless possibilities for your website projects! (Read More about CSS Variable)

Top comments (0)