CSS Variables : The Key to Empowering Your Stylesheets #1

CSS Variables – The ability to produce dynamic and customisable design effects is essential in the field of web development. Custom properties, or CSS variables, provide a way to this realm which allows developers to specify reusable values within stylesheets and modify them dynamically during runtime. This blog post will explore CSS variables with a practical example that highlights their dynamic capability.

Understanding CSS Variables

A stylesheet’s reusable values can be defined and used throughout by using CSS variables. They are declared using the — prefix followed by a name, typically within the :root pseudo-class for global availability. They can be used to store values like fonts, colors, width, height etc. These variables can even be used across other files once they are defined in the CSS code.

This is how a CSS variable is defined:

CSS
:root {
  --main-color: #3498db;
}

In this example, we’ve defined a variable named –main-color and its value is #3498db. We’ve declared it within the :root pseudo-class, which ensures that the variable is accessible everywhere in the CSS code.

How to Use CSS Variables

Once defined, you can use CSS variables anywhere in your CSS code by using the var() function to access them.

Var():

The CSS variable var() allows you to enter the value of a custom property to replace part of the value of another property..

Syntax :

CSS
var(--custom-property);

Example :

CSS
.element {
  color: var(--main-color);
}

In this example, we are using the –main-color variable to set the text color of an element. If you decide to change the main color later on, all you can do is update the value of the variable, and it will automatically reflect across all elements where it’s used.

Theming with CSS Variables

Let’s see how CSS variables can be used to create a theming system for a website. We’ll create variables for the main color and use them on various components.

CSS
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
}

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

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

In this example, we have defined –primary-color and –secondary-color variables. Then we have  applied these colors to the background and text color of the header and button elements, respectively.

Example: Creating Dynamic Theme Colors

Output of the example will be like this :

CSS variables example

Consider a situation where you would like to design a webpage where the theme colour changes dynamically. You want to be able to provide users the option to click a button and then see the page’s entire colour scheme change. Let’s see how CSS variables can make this possible.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Variables</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header class="header">
    <h1>Dynamic Theme - CSS Variables</h1>
  </header>
  
  <button id="changeColorBtn">Change Theme Color</button>

  <script src="script.js"></script>
</body>
</html>

CSS
:root {
  --primary-color: #3498db;
}

.header {
  background-color: var(--primary-color);
  color: white;
  padding: 20px;
  text-align: center;
}

button {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  margin: 20px;
  border-radius: 5px;
}

Dynamic Changes with CSS Variables

CSS variables will change dynamically with JavaScript, which makes it one of its most powerful capabilities. This allows for dynamic theming, user preferences, or even animations.

JavaScript
document.getElementById('changeColorBtn').addEventListener('click', function() {
  // Generate a random hex color
  var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
  
  // Set the random color as the new primary color
  document.documentElement.style.setProperty('--primary-color', randomColor);
});

Let’s learn the JavaScript code step by step:

document.getElementById(
‘changeColorBtn’) :
This code selects the HTML element with the ID changeColorBtn. There most likely is an HTML button element in the content with this ID.

.addEventListener(‘click’, function() { … }):
This method adds an event listener to the button element selected in the previous step by ID (changeColorBtn). when the button is clicked, then executes the function provided as the second argument

var randomColor =
‘#’ + Math.floor(Math.random()*16777215)
.toString(16); :
This code generates a random hexadecimal color code. Here’s how it functions:

  • Math.random():
    This function generates a random floating-point number greater than or equal to 0 and less than 1. It’s important to note that  Math.random() generates pseudo-random numbers, which means that whereas the order of the numbers it produces appears random,
  • Math.floor():
    This function rounds down to the nearest integer. e.g
JavaScript
var number1 = 20.8;
	var number2 = 17;
	var roundedNumber1 = Math.floor(number1); // roundedNumber1 will be 20
	var roundedNumber2 = Math.floor(number2); // roundedNumber2 will be 17

Math.floor(number1) rounds down 20.8 to 20. Math.floor(number2)  returns 17 as 17 is already an integer.

  • * 16777215:
    This section makes sure that the generated random number is inside the range of appropriate values for hexadecimal colours. (from #000000 to #FFFFFF).
  • .toString(16):
    The toString(16) method provides a hexadecimal representation of the generated random number.  This converts the RGB value to a six-digit hexadecimal string.
  • ‘#’ + …:
    Finally, the hash symbol (#) is concatenated with the hexadecimal color string, creating a valid hexadecimal colour code for CSS

document.documentElement
.style.setProperty(
‘–primary-color’, randomColor); :
This line sets the randomly generated colour as the value of the CSS variable – primary-color. Here’s what’s happening:

  • document.documentElement:
    This selects the root element of the HTML document, tag <html>.
  • .style.setProperty():
    This method sets a CSS property on the selected element( i.e in our example its Button ). In this case, it’s setting the value of the –primary-color CSS variable.
  • ‘–primary-color’:
    This is the CSS variable name we have set .
  • randomColor:
    randomColor is typically a variable name used to store a randomly generated color value.This value is often represented as a hexadecimal color code.

Exploring the Example

This example shows a webpage with a button and a header. The background colour of the button and the header are customised using the –primary-color CSS variable, which has a default value of #3498db. A JavaScript script creates a random hexadecimal colour code upon clicking the button, which is then assigned as the new value of the –primary-color variable. As a result, users are given an interesting and interactive experience as the theme colour of the button and header dynamically changes.

CSS Variable Advantages

Modification and reuse: CSS variables allow you to set the same values ​​and reuse style sheets. This will reduce duplication and make it easier to update styles globally, making your code more efficient and easier to maintain.

Dynamic Styling: CSS variables can be modified with JavaScript, allowing for dynamic themes, user preferences, and interactive style features without rewriting CSS rules. This makes it easy to react to user interactions and application behaviour.

Scoped Variables: CSS variables can be scoped to certain components or selectors, giving you more control over where they’re applied and preventing unexpected side effects. This helps to encapsulate style logic while maintaining a clear separation of concerns.

Calculation and Interpolation: CSS variables support calculation and interpolation, so you can do mathematical operations, concatenate values, and build more dynamic styles. This increases the versatility and expressiveness of your stylesheets, allowing for complex layout changes and responsive designs.

Consistency and Theming: CSS variables provide for consistent design throughout an entire website or application by centralising essential properties like colours, typefaces, and spacing. They also make it easier to design and manage themes because theme-specific variables may be defined and shifted out with few changes to the underlying styles.

Ease of Maintenance and Updates: CSS becomes more manageable and updateable by abstracting values into variables. Changing the value of a variable can immediately propagate changes to all elements that use it, reducing the risk of errors and speeding up development iterations.

Browser Compatibility: CSS variables work well in newer web browsers, so they can be used to build new web applications without any problems. They are supported by many browsers and are reliable. Some older web browsers might not be able to use CSS variables, but there are ways to give them different designs using special techniques.

Conclusion

In web development, CSS variables offer a versatile and effective method of managing styles. By defining reusable values and applying them dynamically, developers can create more maintainable and customizable websites. CSS variables provide an extensive toolset to improve the style capabilities of your online projects, whether the focus is on theming, responsiveness, or animation. To fully utilise them in your designs, begin integrating them into your CSS workflow!      

   

Optimizing Web Design with CSS Variables: Your Ultimate Guide #2
Understanding CSS Functions: A Comprehensive Guide #1
CSS Variables : The Key to Empowering Your Stylesheets #1
Mastering the Art of CSS Translate Property: A Comprehensive Guide with 6 examples
Introduction to CSS Animation: Bringing Websites to Life #1
Understanding CSS Progress Bars: A Comprehensive Guide #1
Exploring the :has() Selector in CSS: A Comprehensive Guide with 9 Examples
Top 5 Essential Tips for Writing Better CSS #1

CSSHTMLJavascriptWeb design

Recent Blogs

Mastering Local Storage in Web Development: 8 Practical Examples, From Novice to Expert! #3

Local storage is a useful web development tool that enables developers to save data within the user’s browser. In this article, we’ll look at different features of local storage, starting with beginner-level examples and continuing to more complex techniques. By the end of this guide, you will have a basic understanding of how to successfully […]

CSSHTMLJavascriptWeb Storage

Easy Guide to Excel’s INDIRECT Function #1

How to Use Excel’s INDIRECT Function In the Excel, the INDIRECT function is a versatile tool that can considerably improve your spreadsheet capabilities. Whether you’re a data analyst, financial planner, or casual user, knowing how to use the INDIRECT function will help you optimise workflows and offer dynamic flexibility to your data management. This blog […]

ExcelMicrosoft

12 Essential Design Principles Explained: Your Comprehensive Manual

Design principles are basic ideas and rules that direct the process of creating visually beautiful, useful, and efficient designs in a variety of fields

Design PrinciplesUi Design

Supercharge Your Marketing Strategy with Excel’s SUMPRODUCT #1

What is SUMPRODUCT in Excel? SUMPRODUCT function is an effective and flexible tool that’s mainly utilised for summing the products of comparable ranges or arrays. This function takes the relevant elements from the supplied arrays, multiplies them, and then adds the results together. Syntax : =SUMPRODUCT(array1, [array2], [array3], …) Example 1: Simple Multiplication and Sum […]

ExcelMicrosoft