search
HomeWeb Front-endCSS TutorialThe Big Gotcha With Custom Properties

The Big Gotcha With Custom Properties

Recently I found that many people (including myself) are confused by this feature of CSS custom attributes, so I decided to record it.

Let's add a few custom properties in CSS:

 html {
  --color-1: red;
  --color-2: blue;
}

We use them immediately to create a background gradient:

 html {
  --color-1: red;
  --color-2: blue;

  --bg: linear-gradient(to right, var(--color-1), var(--color-2));
}

Now suppose there are two divs on the page:

<div></div>
<div></div>

Let's style them:

 div {
  background: var(--bg);
}

This works completely! marvelous!

Now let's modify the style. I don't want it to change from red to blue, I want it to change from green to blue. It's very simple, I updated the red to green:

 html {
  --color-1: red;
  --color-2: blue;

  --bg: linear-gradient(to right, var(--color-1), var(--color-2));
}
div {
  background: var(--bg);
}
.variation {
  --color-1: green;
}

invalid! (The sirens are loud, the horns are loud, and domestic animals are hiding everywhere).

Friends, this doesn't work.

As far as I understand, the problem is that --bg has never been declared on any div. It can use --bg because it is declared at a higher level, but when it is used, its value has been locked. Just because you changed the other attributes used when --bg declaration does not mean that the attribute will look for all the locations where it is used as a dependency and update everything that uses it.

Alas, this explanation doesn't feel right. But this is the best explanation I can think of.

Solution? Well, there are a few.

Solution 1: Limit the variable scope to where it is used.

You can do this:

 html {
  --color-1: red;
  --color-2: blue;
}

div {
  --bg: linear-gradient(to right, var(--color-1), var(--color-2));
  background: var(--bg);
}
.variation {
  --color-1: green;
}

Now --bg is declared on both divs, and changes to --color-1 dependencies do work.

Solution 2: Set selectors for most variables with comma separated.

Suppose you did the common operations of setting a bunch of variables in :root . Then you run into this problem. You can simply add extra selectors to the main declaration to make sure you hit the correct range.

 html,
div {
  --color-1: red;
  --color-2: blue;

  --bg: linear-gradient(to right, var(--color-1), var(--color-2));
}
div {
  background: var(--bg);
}
.variation {
  --color-1: green;
}

In some other examples that may not be too far-fetched, it might look like this:

 :root, 
.button,
.whatever-it-is-a-bandaid {
  --padding-inline: 1rem;
  --padding-block: 1rem;
  --padding: var(--padding-block) var(--padding-inline);
}

.button {
  padding: var(--padding);
}
.button.less-wide {
  --padding-inline: 0.5rem;
}

Solution 3: Comprehensive Mode

Go to his - put variables everywhere.

 * {
  --access: me;
  --whereever: you;
  --want: to;

  --hogwild: var(--access) var(--whereever);
}

This is not a good solution. I've heard a chat recently where one of the medium-sized sites was delayed by 500ms due to page rendering, because every draw of the page requires all attributes to be calculated. It "works", but this is one of the few examples where you can cause legitimate performance issues through selectors.

Solution 4: Introduce new "default" properties and fallback

All the credit here is credited to Stephen Shaw, who I saw first in his exploration of all of this content.

Let's go back to where we first demonstrated this question:

 html {
  --color-1: red;
  --color-2: blue;

  --bg: linear-gradient(to right, var(--color-1), var(--color-2));
}

What we have to do is give ourselves two things:

  1. A way to cover the entire background
  2. A way to cover part of a gradient background

So we have to do this:

 html {
  --color-1: red;
  --color-2: blue;
}
div {
  --bg-default: linear-gradient(to right, var(--color-1), var(--color-2));
  background: var(--bg, var(--bg-default));
}

Note that we do not declare --bg at all. It just sits there waiting for a value, and if it gets a value, it is the value of "winning". But if not, it will fall back to our --bg-default . Now……

  1. If I set --color-1 or --color-2 , it replaces that part of the gradient as expected (as long as I do this on a selector that touches one of the divs).
  2. Alternatively, I can set --bg to reset the entire background to whatever I want.

It feels like a good way to deal with it.

Sometimes there is indeed an error in CSS custom properties. But that's not one of them. Even if it's a bit like a bug to me, obviously it's not. Just one of those things you have to know.

The above is the detailed content of The Big Gotcha With Custom Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Two Images and an API: Everything We Need for Recoloring ProductsTwo Images and an API: Everything We Need for Recoloring ProductsApr 15, 2025 am 11:27 AM

I recently found a solution to dynamically update the color of any product image. So with just one of a product, we can colorize it in different ways to show

Weekly Platform News: Impact of Third-Party Code, Passive Mixed Content, Countries with the Slowest ConnectionsWeekly Platform News: Impact of Third-Party Code, Passive Mixed Content, Countries with the Slowest ConnectionsApr 15, 2025 am 11:19 AM

In this week's roundup, Lighthouse sheds light on third-party scripts, insecure resources will get blocked on secure sites, and many country connection speeds

Options for Hosting Your Own Non-JavaScript-Based AnalyticsOptions for Hosting Your Own Non-JavaScript-Based AnalyticsApr 15, 2025 am 11:09 AM

There are loads of analytics platforms to help you track visitor and usage data on your sites. Perhaps most notably Google Analytics, which is widely used

It's All In the Head: Managing the Document Head of a React Powered Site With React HelmetIt's All In the Head: Managing the Document Head of a React Powered Site With React HelmetApr 15, 2025 am 11:01 AM

The document head might not be the most glamorous part of a website, but what goes into it is arguably just as important to the success of your website as its

What is super() in JavaScript?What is super() in JavaScript?Apr 15, 2025 am 10:59 AM

What's happening when you see some JavaScript that calls super()?.In a child class, you use super() to call its parent’s constructor and super. to access its

Comparing the Different Types of Native JavaScript PopupsComparing the Different Types of Native JavaScript PopupsApr 15, 2025 am 10:48 AM

JavaScript has a variety of built-in popup APIs that display special UI for user interaction. Famously:

Why Are Accessible Websites so Hard to Build?Why Are Accessible Websites so Hard to Build?Apr 15, 2025 am 10:45 AM

I was chatting with some front-end folks the other day about why so many companies struggle at making accessible websites. Why are accessible websites so hard

The `hidden` Attribute is Visibly WeakThe `hidden` Attribute is Visibly WeakApr 15, 2025 am 10:43 AM

There is an HTML attribute that does exactly what you think it should do:

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment