


The Surprising Details of CSS Variables - Using var() and Cool Examples
Nov 15, 2024 am 05:49 AMThis is the second half of my CSS Variable post, the first half is here.
In this article we'll look into the details of var(). And two cool examples:
- Animation using CSS Variables
- Pure CSS dark mode toggle with system setting detection
Using var()
The var() accesses custom property values (CSS variables). Its syntax is as follows:
var( <custom-property-name>, <fallback-value>? )
Basic Rules
The first parameter must be a CSS variable: Direct values, such as var(20px), will result in an error, as var() only accepts custom property names.
var() cannot replace property names: In other words, you cannot write something like var(--prop-name): 20px; because var() is limited to use in property values only.
.foo { margin: var(20px); /* Error, 20px is not a CSS variable */ --prop-name: margin-top; var(--prop-name): 20px; /* Error, cannot use var() this way */ }
Detailed Behaviors
var(--b, fallback_value) Fallbacks: The second parameter acts as a fallback value, used when --b is invalid.
var(--c,) Syntax with an Empty Fallback: If the fallback value is left empty, the syntax remains valid and will default to an empty value if --c is invalid.
Multiple Comma: In var(--d, var(--e), var(--f), var(--g)), everything after the first comma is treated as fallback, so if --d is invalid, the var() expression evaluates var(--e), var(--f), var(--g) as one fallback, to determine the result.
var() as a Complete CSS Token: The function acts as a complete CSS token, like 20px would. Therefore, var(--size)var(--unit) will not create 20px and is considered invalid.
Using initial with CSS Variables: Assigning initial to a CSS variable means it is invalid. To display initial as a value, it must be placed in the fallback.
url() and var() Usage: Since url() is treated as a complete CSS token, you need to define the full url() within the variable.
:root { /* 1. */ margin: var(--b, 20px); /* Uses 20px if --b is invalid */ /* 2. */ padding: var(--c,) 20px; /* Falls back to 20px if --c is invalid */ /* 3. */ font-family: var(--fonts, "lucida grande", tahoma, Arial); /* Uses fallback font stack if --fonts is invalid */ /* 4. */ --text-size: 12; --text-unit: px; font-size: var(--text-size)var(--text-unit); /* Invalid, as it does not resolve to 12px */ /* 5. */ --initialized: initial; background: var(--initialized, initial); /* Results in background: initial */ /* 6. */ --invalid-url: "https://useme.medium.com"; background: url(var(--invalid-url)); /* Invalid, as url() cannot parse var() */ --valid-url: url(https://useme.medium.com); background: var(--valid-url); /* Correct usage */ }
Variable Resolution and Scope
CSS variables, like other CSS properties, follow CSS-specific rules for scope and specificity. Understanding how these factors affect CSS variables allows for more precise control.
Global and Scoped Variables:
Variables defined in :root are applied globally, while those defined in selectors have a more limited scope.
:root { --main-color: blue; /* Globally applied */ } .container { --main-color: green; /* Scoped, applies only within .container */ }
Priority by Specificity:
Higher specificity will override lower specificity for CSS variables.
var( <custom-property-name>, <fallback-value>? )
.foo { margin: var(20px); /* Error, 20px is not a CSS variable */ --prop-name: margin-top; var(--prop-name): 20px; /* Error, cannot use var() this way */ }
In this example, the background color of .box remains white, as --background was resolved to rgb(255, 255, 255) before .box redefined --green: 0.
Reevaluating Variables with Pseudo-Classes:
Variables change based on pseudo-class states when defined at the same level.
:root { /* 1. */ margin: var(--b, 20px); /* Uses 20px if --b is invalid */ /* 2. */ padding: var(--c,) 20px; /* Falls back to 20px if --c is invalid */ /* 3. */ font-family: var(--fonts, "lucida grande", tahoma, Arial); /* Uses fallback font stack if --fonts is invalid */ /* 4. */ --text-size: 12; --text-unit: px; font-size: var(--text-size)var(--text-unit); /* Invalid, as it does not resolve to 12px */ /* 5. */ --initialized: initial; background: var(--initialized, initial); /* Results in background: initial */ /* 6. */ --invalid-url: "https://useme.medium.com"; background: url(var(--invalid-url)); /* Invalid, as url() cannot parse var() */ --valid-url: url(https://useme.medium.com); background: var(--valid-url); /* Correct usage */ }
Next, let’s explore some advanced use cases for CSS variables:
Usage Example A: Animations
CSS variables cannot be directly animated because the browser cannot infer the data type. To resolve this, use @property to define the variable's type and initial value, enabling the browser to understand how to animate the variable.
:root { --main-color: blue; /* Globally applied */ } .container { --main-color: green; /* Scoped, applies only within .container */ }
:root { --main-color: blue; } .section { --main-color: green; /* Overrides :root definition */ } .section p { color: var(--main-color); /* Shows green */ } p { color: var(--main-color); /* Shows blue */ }
Adding a Manual Toggle that Aligns with System Preferences
While the system setting controls the theme by default, we may want to give users the option to manually toggle between light and dark themes. To achieve this, we can add a checkbox to toggle the state. Ideally, when the checkbox is selected, it indicates dark mode, and when unselected, it represents light mode.
However, CSS cannot automatically detect system settings and change the checkbox state accordingly, especially in dark mode. To handle this limitation, we can use CSS variables and the :has() selector to control theme switching based on the checkbox state.
I wanted to try achieving this entirely with CSS, but since a user’s system may be set to either light or dark mode, CSS alone can’t automatically check the checkbox in dark mode.
If we can’t move the mountain, we’ll route the path. Here’s the workaround:
- We’ll use CSS to create a toggle switch, where the visual “OFF” state represents light mode, and “ON” represents dark mode.
When system sets to light mode: When the checkbox is unselected, it corresponds to the “OFF” state (light mode). When selected, it corresponds to the “ON” state (dark mode).
When system sets to dark mode: Since the system preference is reversed, the visual state also inverts. When the checkbox is unselected, it corresponds to “ON” (dark mode). When selected, it corresponds to “OFF” (light mode).
To achieve this effect, we need two main elements:
First: Variables that Change Based on System Setting and Checkbox State
var( <custom-property-name>, <fallback-value>? )
Second: Toggle Behavior Based on System Settings for checked State and ON/OFF Representation
The light and dark mode CSS properties are reversed depending on the system setting.
.foo { margin: var(20px); /* Error, 20px is not a CSS variable */ --prop-name: margin-top; var(--prop-name): 20px; /* Error, cannot use var() this way */ }
Simplifying Variable Setup with CSS Variable Tricks
Here we’ll use Space Toggle technique to simplify variable settings. Here’s the code, followed by an explanation of how it works:
:root { /* 1. */ margin: var(--b, 20px); /* Uses 20px if --b is invalid */ /* 2. */ padding: var(--c,) 20px; /* Falls back to 20px if --c is invalid */ /* 3. */ font-family: var(--fonts, "lucida grande", tahoma, Arial); /* Uses fallback font stack if --fonts is invalid */ /* 4. */ --text-size: 12; --text-unit: px; font-size: var(--text-size)var(--text-unit); /* Invalid, as it does not resolve to 12px */ /* 5. */ --initialized: initial; background: var(--initialized, initial); /* Results in background: initial */ /* 6. */ --invalid-url: "https://useme.medium.com"; background: url(var(--invalid-url)); /* Invalid, as url() cannot parse var() */ --valid-url: url(https://useme.medium.com); background: var(--valid-url); /* Correct usage */ }
The key here is in the line --background-color: var(--light, #fbfbfb) var(--dark, #121212);. Here, the background color depends on the values of --light and --dark, effectively simulating an if/else in the property.
How does it work? Initially, --light: var(--ON); and --ON: initial; make --ON an invalid state. Meanwhile, --OFF is set as an empty string. When applied to var(--light, #fbfbfb) var(--dark, #121212), the invalid --light variable will default to #fbfbfb, and the valid --dark variable (empty) allows --background-color to equal #fbfbfb.
All the other color variables follow the same logic, adjusting based on the state of --light and --dark. This way, each color variable only needs to be defined once.
Switching states becomes simple. If dark mode is active, use --light: var(--OFF); and --dark: var(--ON);. In light mode, reverse them. Though not immediately intuitive, this method is currently the most effective with CSS. If there are better solutions, they are worth exploring.
Complete example: CodePen Example
Summary
CSS continues to evolve, with CSS variables available in major browsers since 2016. New features like @property and :has() are expanding CSS variables’ flexibility even further. Combined with other new tools, CSS variables are becoming more powerful—for instance, they can now enhance scroll-driven animations to create visually dynamic effects. As a core element for storing state in CSS, much like variables in any programming language, a solid understanding of CSS variables will prove invaluable for more sophisticated styling and design down the road.
References
- https://stackoverflow.com/questions/42330075/is-there-a-way-to-interpolate-css-variables-with-url/42331003#42331003
- https://kizu.dev/cyclic-toggles/#was-this-always-possible
- https://dev.to/afif/what-no-one-told-you-about-css-variables-553o
- https://hackernoon.com/cool-css-variable-tricks-to-try-uyu35e9
- https://lea.verou.me/blog/2020/10/the-var-space-hack-to-toggle-multiple-values-with-one-custom-property/
The above is the detailed content of The Surprising Details of CSS Variables - Using var() and Cool Examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
