top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

CSS Variables

Introduction

The web design and development world has witnessed great advancement in the last couple of decades. The days of writing common code and manually updating each instance with a specific value are the past. This article will take you on an exploratory journey of Cascading Style Sheets (CSS) - one of the game-changing aspects of CSS Variables. We’ll look into their usability and compatibility with JavaScript and React and compare them to SCSS Variables. Let’s dive straight into CSS variables. 

Overview

With the evolution of CSS, there’s been a gradual shift from static to dynamic style sheets. This is where CSS Variables come into the picture. We will discuss in detail the changes in the writing and managing processes of CSS. 

What are CSS Variables? 

CSS Variables are entities within the programming work, with specified values defined by CSS authors.  They have valuable usage throughout the document. They are predefined with custom property notation (for instance, '--main-color: black;'). Once you specify a CSS variable, you can use the 'var()' function to reference it anywhere in your stylesheet.

For instance, here is a simple usage of the CSS variable for color:

Here, `--main-color` is the variable holding the color value `#ff6347`. Then we use `var(--main-color)` to apply this color as the background. The output would be a webpage with a background color of `#ff6347`.

When to Use CSS Variables?

CSS Variables are useful tools in several practical scenarios. They offer a level of abstraction and reusability that can simplify CSS and make your code more sustainable. Here are some cases where you may find CSS Variables particularly useful.

1. Thematic Consistency

Often, you might want to maintain thematic consistency across your website. This could be a certain color scheme, font style, or spacing pattern. CSS Variables are perfect for defining these values once and then using them throughout your stylesheet. 

For instance, consider you want to set a color scheme for a website.

Here, you've defined a primary and secondary color. These are used as the background and text color of the body, respectively.

2. Responsive Design

Responsive design is another area where CSS Variables can be a game-changer. You can define variables for different layouts and switch between them using media queries.

Here, the header height changes based on the viewport width. For viewports wider than 600px, the height is 80px; otherwise, it's 60px.

3. Dark Mode/Light Mode Toggle

One of the trending uses of CSS Variables is in implementing a dark mode/light mode toggle. You can define a set of colors for light mode and another for dark mode, then switch between them with a single class change.

In light mode, the background is white and the text is black. When the `dark-mode` class is added to the body, the background turns black and the text becomes white.

Inline CSS

Applying styles directly to HTML components using the style property is called inline CSS. It's the easiest technique to style an element because you can apply styles directly in HTML without referring to a stylesheet or specifying internal styles.

Consider a blog post where you wish to highlight a paragraph. The text should be green and italicized. You can use inline CSS in HTML like this:

It specifies green and italic text in the text tag.

This solution gives CSS the highest priority but lacks reusability and might lead to code repetition in larger projects. Thus, minor, one-time stylistic modifications are advised.

The var() Function

The `var()` function is a fundamental tool for leveraging CSS Variables in stylesheets. It serves as the link between variable declarations and their use in the styles.

Conceptually, the `var()` function works like a placeholder. When you place `var(--your-variable)` in your CSS, you're saying, "insert the value of `--your-variable` here." This happens at runtime in the browser. The CSS engine looks for the value of `--your-variable` in the current scope and replaces `var(--your-variable)` with that value.

One of the unique features of the `var()` function is its ability to accept a fallback value, which acts as a safety net. If the CSS engine cannot find the specified variable or if the value is invalid, it will use the fallback value instead. This is particularly useful in situations where certain variables may not be defined in all contexts, but you still want to ensure that a valid style is applied.

An important aspect of `var()` is that it allows CSS to be dynamic in a way that wasn't possible before CSS Variables. Since it` retrieves the value at runtime, you can change the value of a CSS Variable with JavaScript and the `var()` function will use the updated value.

The `var()` function is the mechanism by which CSS Variables are applied, bridging the gap between static styles and dynamic context-dependent values. It allows stylesheets to be more flexible, maintainable, and responsive to user interactions and other dynamic conditions.

Here's an example:

In the code above, the `var(--main-color)` function is used to insert the value of `--main-color`, which is `coral`, as the body's background color.

Use of calc() with var()

The `calc()` function in CSS lets you perform calculations to determine CSS property values. It becomes more powerful when used with CSS variables. Say, you have a base font size defined as a CSS variable and want to use different multiples of it:

Here, the `h1` elements will have a font size of 32px, while the `p` elements will maintain the base font size of 16px.

CSS Variables List

A CSS Variables list completely lists all CSS custom properties or variables you've defined in your stylesheet. It is good practice to create this list for several reasons:

1. Improved Maintenance

Having a list of all CSS Variables makes it less complicated and is a good way to maintain and replace your code. You can quickly discover the context in which a variable is described and apprehend its use throughout the task. This is especially beneficial in large projects where dozens of variables are probably in use.

2. Enhanced Readability

A CSS Variables listing improves clarity by acting as a reference manual. Co-developers can easily make out the set of variables you've defined and their intended usage. This promotes consistent use of variables across the project, enhancing the overall quality of the code.

3. Encourages Consistency

By having a CSS Variables list, you encourage consistency in your design. It's less difficult to reuse current variables than to create new ones. This reduces the hazard of inconsistent styling throughout distinct parts of your website.

4. Reduces Duplication

A well-maintained list of CSS Variables can prevent the creation of duplicate variables. Without a listing, you or other developers might not be aware of all the present ones, leading to useless repetition.

An example of how to maintain a CSS Variables list.

Here, all the variables are defined at the `:root` level, making them globally available. They are grouped by their purpose, making the list more readable and easier to maintain.

Maintaining a CSS Variables list is a crucial part of good coding practice. It enhances readability, reduces duplication, and promotes consistency across the website.

CSS Variables in JavaScript

One of the biggest benefits of CSS Variables is their interoperability with JavaScript. They can be dynamically updated with JavaScript, providing the ability to change styles based on user interaction or other dynamic factors.

The following example explains the concept further:

Here, the button's background color will change to `#9b59b6` when the mouse hovers over it.

CSS Variables in React

React is widely recognized as a highly popular JavaScript library that is commonly used for constructing user interfaces, with a primary focus on single-page applications. The platform enables developers to efficiently build and update web applications that can handle large amounts of data and respond quickly to changes.

React blurs the traditional separation between CSS and JavaScript, as it enables writing CSS within JavaScript. The achievement of enhancing styles with JavaScript logic is made possible through a concept known as CSS-in-JS.

CSS Variables are particularly beneficial when used in a React environment. The feature allows users to set dynamic values in their styles, giving them the ability to control these values through JavaScript. In React, the dynamic nature of the UI, which is closely tied to the application's state, makes this aspect significant.

Here's an example of how you might use CSS Variables in React:

Here, the `mainColor` state controls the `--main-color` CSS Variable. When the button is clicked, `setMainColor` updates the state, which in turn updates the CSS Variable, causing the color to change in the UI.

React's ability to work closely with CSS Variables is another reason why it is an invaluable tool for modern web developers. They allow for greater flexibility and dynamism in your styles and perfectly align with the dynamic nature of React applications.

CSS Variables vs SCSS Variables

While CSS and SCSS variables assist you in keeping and reusing values for your stylesheets, they are characterized differently and have special capabilities. Here's a comparative study of the two:

- Scope: 

  • CSS variables are scoped to the selector they are declared in and inherited by using any nested selectors.

  • SCSS variables can have local or global scope, depending on how and where they are declared.

- Runtime:

  • CSS variables are processed at runtime, meaning they can be updated using JavaScript and modifications will immediately come into effect inside the browser.

  • SCSS variables are processed at compile time. Once the SCSS is compiled into CSS, the variables are replaced with their values and cannot be modified thereafter.

- Browser Handling: 

  • Since the browser handles CSS variables directly, any CSS property can use them.

  • SCSS variables require a preprocessor to compile the code into CSS. The browser doesn't interpret SCSS variables; it only sees the compiled CSS.

- Compatibility: 

  • CSS variables are compatible with all modern browsers but not with Internet Explorer.

  • Since SCSS variables are compiled to standard CSS, they work in all browsers.

- Value Access: 

  • You can inspect and modify CSS variables directly in browser development tools.

  • You can't inspect or modify SCSS variables in the browser because they don’t exist in the compiled CSS.

- Usage Dynamics:

  • CSS variables allow for dynamic changes, making them ideal for creating adjustable topics or designs that react to consumer input.

  • SCSS variables are suitable for values that don’t want to change once the page is loaded, which include colors, fonts, or fixed sizes.

Conclusion

Modern web development requires front-end developers to master CSS Variables. Reusable values in CSS Variables solve traditional CSS's constraints. This improves code efficiency and maintainability. JavaScript allows developers to create interactive, dynamic web experiences. CSS Variables naturally integrate with React's component-based architecture, making them important. The ability to quickly switch themes or dynamically alter styles with CSS Variables is vital as user experience becomes more important. In conclusion, CSS Variables revolutionize web development and styling. They will make your web apps more adaptable, responsive, and user-friendly.

FAQs

1. How does CSS handle undefined variables?  

When a CSS variable is undefined or invalid, it will simply act as if the property that uses it doesn't exist. This helps keep the rest of the styling intact.

2. What are the performance implications when using CSS variables?  

Generally, the performance impact of using CSS variables is negligible. However, excessive usage with complex calculations might lead to minor performance issues in certain scenarios.

3. What is the available CSS variable support?

Chrome fully supports CSS Variables (Custom Properties) in versions 49-114. They are also fully supported in Safari versions 10-16.4 and partially in versions 9.1-9.1.

Leave a Reply

Your email address will not be published. Required fields are marked *