Why do CSS Variables have different syntax for setting and getting values?

When we use CSS Variables, also known as CSS Custom Properties, the syntax for setting and getting values is different.

To set a value for --my-custom-width, we use:

:root {
  --my-custom-width: 120px;
}

Similarly, to get the value of --my-custom-width, we use the var() function:

.my-div {
  width: var(--my-custom-width);
}

It might be tempting to write it this way:

.my-div {
  width: --my-custom-width;
}

Answer №1

After delving into the world of CSS Custom Properties back in late 2017, I have finally grasped their true essence and the importance of the var() function...

Contrary to common belief, they are not simply variables that directly represent CSS values.

CSS Custom Properties are exactly what their name suggests - they are essentially new CSS properties that do not have assigned values initially.


In the realm of CSS, an example of a variable truly representing a value is seen with the currentColor property.

An instance showcasing this is:

.my-div {
  border: 1px dashed currentColor;
}

Unlike variables like currentColor, CSS Custom Properties serve as unique, named, null-value-properties...

...and these specially crafted properties can be reused just like standard properties such as width, height, and color, with the flexibility to set and reset values in different contexts.

For example:

/* My custom property is --my-custom-width but I want this
   property to hold different values in different contexts */

.left-two-thirds-of-page {
  --my-custom-width: 120px;
}

.right-third-of-page {
  --my-custom-width: 60px;
}

.my-div {
  width: var(--my-custom-width);
}

This highlights why the var() function plays a crucial role - it doesn't merely provide "the custom property", but rather retrieves the current value associated with the custom property and presents that value.


Additonal Reflections:

In retrospect, one might ponder whether the concept of name-value relationship would have been clearer if CSS Custom Properties were labeled as:

CSS Custom Property Names

and referred to their corresponding function as:

value()

thus leading to syntax like:

value(--my-custom-property-name)

Extending this idea, we could potentially utilize the value() function (or var() function) not only on custom properties but on any property.

For instance:

width: value(height);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhancing the aesthetics: Stylish blue borders around Bootstrap

After successfully setting up bootstrap-select, I have noticed that blue borders are showing in two specific instances: 1) within the dropdown menu 2) when a new value is selected I have made some adjustments but the issue persists. Can someone please p ...

What could be causing my Next.js layout to re-render?

I currently have a basic root layout set up in Nextjs (app router) that displays a navigation bar and the child components underneath it. ROOT LAYOUT import "./globals.css"; import type { Metadata } from "next"; import { Inter } from & ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

The toggle button requires two clicks to activate

I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start? Below is t ...

Issue arises after injecting HTML element into the DOM due to memory constraints and display inconsistencies

Upon executing the following script in Firefox... var d = $("<div class='test'></div>"); d.hide(); $("body").prepend(d); d.show(); ...and examining the HTML, the inserted element will have the style attribute: style="display: blo ...

How can I make a Bootstrap 4 modal autoplay an iframe on page load?

My website features a full-screen background video that plays upon loading, and I want the same video to play when a user clicks the play button to open a modal. However, my issue is that the modal video (iframe) starts playing in the background as soon ...

Conflict between iOS 7+ swipe back gesture and stateChange animations

When transitioning between states in an AngularJS application, I utilize CSS animations to add visual appeal to the view change. This may involve applying fades or transforms using classes like .ng-enter and .ng-leave. In iOS 7+, users can swipe their fin ...

Using CSS absolute/relative positioning in a flyout menu: Utilizing specific parent properties (such as left, top, width, vertical/horizontal alignment) while disregarding others

I recently encountered a common issue in CSS involving flyout menus with sub-menus that are shown on hover. When attempting to position the sub-menu directly below the parent list item, I used position:relative; on the parent item and position:absolute;top ...

Guide on triggering an open modal when clicking a link using jQuery

Creating a modal popup has always been my goal. After designing the CSS to style it, I found myself stuck as I lack knowledge in JQuery or JavaScript to code the functionality that animates and opens the modal upon clicking a button or link. Despite search ...

Using jQuery, selectively reveal and conceal multiple tbody groups by first concealing them, then revealing them based on

My goal is to initially display only the first tbody on page load, followed by showing the remaining tbody sections based on a selection in a dropdown using jQuery. Please see below for a snippet of the code. //custom JS to add $("#choice").change(func ...

How can I speed up the loading time of my background image?

I have noticed that my background image is loading slowly on my website. I expected it to be cached so that subsequent pages using the same background would load instantly. However, the background image is only loading once the entire page is drawn. My CS ...

Web Essentials is experiencing a problem with minified CSS

Today, while using Web Essentials 2013 for Update 3 with Visual Studio Express 2013 for Web, I encountered an issue with the minified CSS file. The website I am currently working on is built on a Twitter Bootstrap platform and utilizes two separate CSS fil ...

How to make a Material UI Dialog Box automatically expand to fit the Dialog Content Area

In my project, I am working on a Dialog component which has a maximum width and a minimum height. Inside the DialogContent, I want to have a Box element that stretches to fill out the remaining space of the DialogContent. The goal is to have a background i ...

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

What is the best way to incorporate material icons onto a website?

When I attempted to display an icon on my webpage by adding <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> to the index.html file, only the icon name appeared as text instead of the actual ...

Issues with z-index in a multi-column menu using React-Router are causing unexpected behavior

I am currently working on a multi-tier, multi-column menu created using the https://github.com/kontentino/react-multilevel-dropdown library. However, I am facing an issue where the submenu items are appearing under the main items despite several attempts t ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Is it possible to initially design a login page using HTML/CSS and JavaScript, and then integrate VUE into it?

As part of a school project, I am tasked with developing a web-based application for a library system. The goal is to create a platform where librarians can login and manage books by adding, removing, or editing them. My responsibility lies in handling the ...

A straightforward guide on utilizing data-attributes to achieve a linear-gradient background

considering the following input .prettyRange { -webkit-appereance: none; } .prettyRange::-webkit-slider-runnable-track { background: -webkit-linear-gradient(right, #fff 0%, green 50%, #fff 0%); } <input class="prettyRange" type="range" name="cap ...

Footer placement not aligning at the bottom using Bootstrap

I'm having trouble getting my footer to stay at the bottom of my website without it sticking when I scroll. I want it to only appear at the bottom as you scroll down the webpage. Currently, the footer is positioned beneath the content on the webpage. ...