What are CSS custom properties (variables) and how to use them?
Jul 21, 2025 am 02:34 AMCSS custom attributes (i.e. CSS variables) improve development efficiency by storing and reusing style values. The core usage methods include: 1. Use the --variable name syntax to define in:root or specific selectors; 2. Reference variables through the var (--variable name, default value) function; 3. Can dynamically update variable values, support topic switching, responsive design and other scenarios. Their inheritance and cascade rules are consistent with ordinary CSS properties and can be modified through JavaScript runtime to achieve user preferences or dynamic style adjustments.
CSS custom properties, often referred to as CSS variables, are a way to store and reuse values across your stylesheet. They make it easier to manage themes, maintain consistency, and reduce repetition. Unlike traditional CSS, where you had to repeat the same color or font value multiple times, custom properties let you define them once and use them anywhere.

How to Define CSS Custom Properties
You define custom properties using a special syntax: they always start with two dashes ( --
) followed by a name of your choosing. These properties are scoped, meaning where you define them affects where they can be used.
For example:

:root { --primary-color: #007bff; --font-size: 16px; }
Here, we're defining two variables inside :root
, which makes them globally available throughout the document. You can also define variables on more specific selectors if you want them to apply only in certain parts of the page.
A few things to keep in mind:

- Variable names are case-sensitive, so
--color
and--Color
are different. - You can update their values dynamically via JavaScript or media queries.
- They cascade and inherit like regular CSS properties.
How to Use CSS Variables
Once defined, you can use a custom property by referencing it with the var()
function. This function takes the variable name and an optional fallback value if the variable isn't defined.
Example usage:
button { background-color: var(--primary-color); font-size: var(--font-size, 14px); }
In this snippet:
- The button's background color uses our
--primary-color
. - If
--font-size
isn't set somewhere, it falls back to14px
.
This is especially useful for creating themes or allowing user preferences (like dark mode) without duplicating large chunks of CSS.
Also, don't forget that variables work anywhere in CSS — not just in common places like colors or sizes. You could even use them for transition timing, grid layout settings, or complex shadow effects.
Practical Use Cases
Custom properties really shine when managing dynamic styles or themes. Here are some practical applications:
- Theme switching : Define light and dark theme variables and toggle between them.
- Responsive design tweaks : Adjust spacing or font sizes based on screen size by updating variables inside media queries.
- Component-based styleling : Define variables within component containers so child elements can inherit context-specific styles.
Let's say you have a card component. Instead of hardcoding padding or border radius, you can do something like:
.card { --card-padding: 1rem; --card-radius: 8px; padding: var(--card-padding); border-radius: var(--card-radius); }
Now, if you need a variation of the card with different spacing or corner radius, you can simply override those variables in a subclass:
.card.featured { --card-padding: 2rem; }
This keeps your base styles clean and reusable while making overrides simple.
Updating Variables with JavaScript
One of the biggest advantages of CSS variables is that they can be changed at runtime using JavaScript. This opens up possibilities for user-driven style changes or dynamic theming.
To update a variable from JavaScript:
document.documentElement.style.setProperty('--primary-color', '#ff5722');
This would change the --primary-color
variable globally. If you want to target a specific element instead of the root, just select that element first.
You might use this to:
- Let users pick a theme color from a picker.
- Switch to high-contrast mode for accessibility.
- Animate values over time (eg, for interactive UI elements).
Just remember that changing a variable updates all places where it's used — no need to manually update each CSS rule.
Basically that's it.
The above is the detailed content of What are CSS custom properties (variables) and how to use them?. 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)

Hot Topics

Inthisarticle,wewilldiscusshowtodeclareacustomattributeinHTML.CustomattributescanbeusefulinHTMLwhenyouwanttostoresomeadditionalinformationthatisnotpartofthestandardHTMLattributes.ItallowsformoreflexibilityandcustomizationinHTMLandcanhelpmakeyourcodem

This article will take you through CSS variables, talk about how CSS variables work, and introduce how to use inline CSS variables to improve the efficiency of smart layout. I hope it will be helpful to everyone!

The scope of CSS custom properties depends on the context of their declaration, global variables are usually defined in :root, while local variables are defined within a specific selector for componentization and isolation of styles. For example, variables defined in the .card class are only available for elements that match the class and their children. Best practices include: 1. Use: root to define global variables such as topic color; 2. Define local variables inside the component to implement encapsulation; 3. Avoid repeatedly declaring the same variable; 4. Pay attention to the coverage problems that may be caused by selector specificity. Additionally, CSS variables are case sensitive and should be defined before use to avoid errors. If the variable is undefined or the reference fails, the fallback value or default value initial will be used. Debug can be done through the browser developer

The html5 custom attribute "data-*" is used to store custom data applied behind a private page, and the custom data can give the page a better interactive experience (no need to use Ajax or go to the server to query data), the syntax " <element data-*="Specify attribute value (a string)">"; "data-*" attribute consists of two parts: 1. The attribute name should not contain uppercase letters, and there must be at least one character after "data-" ;2. Attribute value, the value can be any string.

CustomAttributes are mechanisms used in C# to attach metadata to code elements. Its core function is to inherit the System.Attribute class and read through reflection at runtime to implement functions such as logging, permission control, etc. Specifically, it includes: 1. CustomAttributes are declarative information, which exists in the form of feature classes, and are often used to mark classes, methods, etc.; 2. When creating, you need to define a class inherited from Attribute, and use AttributeUsage to specify the application target; 3. After application, you can obtain feature information through reflection, such as using Attribute.GetCustomAttribute();

CSS variables improve style maintenance and theme management by defining reusable values. Its core advantages include: 1. Reduce duplication and improve consistency by centrally defining style values; 2. Support dynamic coverage to achieve simple and efficient multi-theme switching; 3. Avoid common traps such as inconsistent naming, overuse, etc. Developers should define global variables in:root, and use scope and fallback values ??to enhance flexibility and readability, while dynamic adjustments are combined with JavaScript to improve user experience.

The core of using CSS variables to achieve topic switching is to define the basic variables and organize the topic structure, and dynamically switch through class names or attributes. The steps are as follows: 1. Define basic variables such as colors, fonts, etc. in root; 2. Create classes that cover variables for different themes (such as dark and light colors); 3. Call variables using var() in CSS rules; 4. Switch class names or attributes through JavaScript to achieve theme changes; 5. Extend variables to font size, rounded corners, shadows and other style attributes. This clear structure and easy maintenance lies in reasonable naming and scope control.

CSS custom attributes (i.e. CSS variables) improve development efficiency by storing and reusing style values. The core usage methods include: 1. Use the --variable name syntax to define in:root or specific selector; 2. Reference variables through the var (--variable name, default value) function; 3. Can dynamically update the variable values, support theme switching, responsive design and other scenarios. Their inheritance and cascade rules are consistent with ordinary CSS properties and can be modified through JavaScript runtime to achieve user preferences or dynamic style adjustments.
