Preface
CSS variables are a powerful feature that can help developers better organize and manage style sheets. In this article, we’ll dive into advanced tips and best practices for CSS variables. By learning how to use variables as calculated values, media queries, and dynamic changes, you’ll be able to better take advantage of the power of CSS variables.
1. Concept
CSS
A variable (also called a custom property) is a CSS
value defined and used in a that can be reused throughout a stylesheet. They provide a flexible way to store and manage values in styles, making style modifications easier and more maintainable.
2. Basic usage
CSS
The basic usage of variables includes defining variables, using variables and modifying the values of variables.
1. Define variables
In CSS
, variables are defined using the – prefix. Variable names can consist of letters, numbers, dashes, and underscores, but they must begin with a letter. Variable definitions are usually placed within the selector's rule set, or :root
defined in the root element ( ) for global use. For example:
:root {
--primary-color: #ff0000;
--font-size: 16px;
}
2. Use variables
When using variables, you need to var()
wrap the variables with functions. Variables can be used anywhere CSS
a property value can be used, such as color, size, margin, etc. For example:
.element {
color: var(--primary-color);
font-size: var(--font-size);
}
3. Modify the value of the variable
The value of the variable can be CSS
dynamically modified in to achieve style changes. The value of a variable can be modified via JavaScript or using pseudo-classes ( :hover
, :focus
etc.). For example:
.element:hover {
--primary-color: #00ff00;
}
Or use JavaScript
to modify the value of a variable:
document.documentElement.style.setProperty('--primary-color', '#00ff00');
3. Naming convention
When we CSS
use variables in , in order to avoid conflicts with existing CSS
properties, we can use custom CSS
variables and choose appropriate naming conventions for them. Properties starting with two dashes ( --
) are considered CSS
variables.
Here are some common CSS
variable naming conventions:
- Use meaningful names: To increase code readability and maintainability, we should choose descriptive names for
CSS
variables. This makes it easier for other developers to understand the purpose and meaning of the variables; - Use lowercase letters and hyphens:
CSS
Variable names should be in lowercase letters and use hyphens (-
) as separators between words. For example,--primary-color
; - Use namespaces: To avoid conflicts with other variables, you can use namespaces to group variables. For example,
--button-primary-color
, wherebutton
is the namespace; - Avoid using abbreviations and abbreviations: Try to avoid using abbreviations and abbreviations for variable names as this may make the code less readable. Choose descriptive names so that other developers can easily understand what the variable means;
- Use a consistent naming convention: It is important to maintain a consistent naming convention throughout your project. Choosing a naming style and sticking to it throughout your project will improve code consistency and readability.
In short, CSS
variable naming conventions should focus on readability, maintainability, and consistency. We can better organize and manage our variables by choosing meaningful names, using lowercase letters and hyphens, using namespaces, and avoiding abbreviations and abbreviations CSS
.
4. Variable value type
In CSS
, CSS
the values of variables can be of various types. Different types will also have subtle differences in usage.
If the variable value is a string, it can be concatenated with other strings, for example:
<!DOCTYPE html>
<html>
<style>
:root {
--primary-content: 'hello';
}
.box:after {
content: '标题 : ' var(--primary-content)
}
</style>
<body>
<div class="box"></div>
</body>
</html>
- achieve effect
If the variable value is a numeric value, it cannot be used directly with the numeric unit, for example:
In the code below, we box2
use calc()
the function in the box to perform a mathematical calculation, multiplying --primary-num
the value of the variable 1
by pixels ( 1px
). This way, you can combine values with units to achieve the correct styling effect. In this way, we can splice values and units to ensure the correctness of the style. And calc()
functions can perform more complex mathematical calculations, such as addition, subtraction, multiplication, division, etc.
<!DOCTYPE html>
<html>
<style>
:root {
--primary-num: 40;
}
.box1 {
background: cadetblue;
padding-top: var(--primary-num)px;
}
.box2 {
background: chocolate;
padding-top: calc(var(--primary-num) * 1px);
}
</style>
<body>
<div class="box1">内容1</div>
<div class="box2">内容2</div>
</body>
</html>
- achieve effect
If the variable value has a unit, it cannot be written as a string, for example:
In the code below, we box1
define the variable value with units as a string in the box. This is invalid because CSS
the attribute expects a numeric unit, not a string. Such a definition will cause the style to be invalid or produce an error. Therefore, when a variable value has a unit, it should be defined as a numeric value, not a string. This ensures that variables CSS
are correctly combined with units when applied to properties.
<!DOCTYPE html>
<html>
<style>
:root {
--border-radius-box1: '20px';
--border-radius-box2: 20px;
}
.box1 {
background: chocolate;
border-radius: var(--border-radius-box1);
}
.box2 {
background: cornflowerblue;
border-radius: var(--border-radius-box2);
}
</style>
<body>
<div class="box1">内容1</div>
<div class="box2">内容2</div>
</body>
</html>
- achieve effect
5. How to understand: root and var()
:root
Pseudo class:
:root
Pseudo-class selectors match the root element of the document tree, usually<html>
the element;:root
Variables defined in pseudo-classesCSS
can be used globally throughout the document;- By
:root
defining variables in pseudo-classes, we can set globalCSS
attribute values for the entire document; - For example, we can use
:root
pseudo-classes to define global colors, font sizes, breakpoint values, etc.
var()
function:
var()
Functions are used to reference and useCSS
the value of variables;- It accepts one parameter, which is the name of the variable to be referenced
CSS
; var()
Functions canCSS
be used on the value of any property, including font size, color, margins, etc.;- By using
var()
functions, we can use the same variable value in different elements and selectors as neededCSS
to achieve unified style management; - For example, we can use
var(--primary-color)
to refer to a globally defined--primary-color
variable.
CSS
This is the basic usage of variables. By defining, using and modifying the values of variables, style reuse, dynamic changes and global control can be achieved. This makes CSS
development more flexible and maintainable. Three cases are provided below, covering the complete code of examples of defining variables, using variables, and modifying the values of variables.
Case 1
In this case, we define two variables --primary-color
and --font-size
and apply them to .element
the color and font size of the element. When the mouse is hovering .element
over the element, --primary-color
the value of the variable will turn green and --font-size
the value of the variable will become 26px
.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-color: #f88604;
--font-size: 22px;
}
.element {
color: var(--primary-color);
font-size: var(--font-size);
}
.element:hover {
--primary-color: rgb(0, 104, 202);
}
</style>
</head>
<body>
<div class="element">Hello, CSS Variables!</div>
</body>
</html>
- achieve effect
Case 2
In this case, we use JavaScript
to monitor window size changes and dynamically modify CSS
the value of the custom property based on the window width. In updateStyles
the function, we window.getComputedStyle
obtain --breakpoint
the value of through the method, and determine whether to apply responsive styles based on the window width.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--breakpoint: 300px;
--font-size: 16px;
--primary-color: #ff0000;
}
.element {
font-size: var(--font-size);
color: var(--primary-color);
}
</style>
<script>
function updateStyles() {
var element = document.querySelector('.element');
var breakpoint = getComputedStyle(document.documentElement).getPropertyValue('--breakpoint');
if (window.innerWidth <= parseInt(breakpoint)) {
element.style.setProperty('--font-size', '14px');
element.style.setProperty('--primary-color', '#00ff00');
} else {
element.style.setProperty('--font-size', '16px');
element.style.setProperty('--primary-color', '#ff0000');
}
}
window.addEventListener('resize', updateStyles);
window.addEventListener('DOMContentLoaded', updateStyles);
</script>
</head>
<body>
<div class="element">Responsive Text</div>
</body>
</html>
- achieve effect
Case 3
In this case, we define a variable --primary-color
and apply it to .element
the color of the element. Through the function JavaScript
in changeColor
, we can modify the value of the variable by clicking the button --primary-color
, thereby changing .element
the color of the element.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-color: orange;
}
.element {
color: var(--primary-color);
}
</style>
<script>
function changeColor() {
document.documentElement.style.setProperty('--primary-color', 'blue');
// document.documentElement.style.setProperty('root变量', '更改的值')
}
</script>
</head>
<body>
<div class="element">Click the button to change color</div>
<button onclick="changeColor()">点击改变颜色</button>
</body>
</html>
- achieve effect
Case 4
In this case, by using CSS
variables, we can dynamically control the style of the button and achieve the mouse tracking effect.
In the code, we define two CSS
variables: --x
and --y
. These two variables represent the abscissa and ordinate of the mouse on the button respectively. Through the method JavaScript
in setProperty
, we can update the values of these two variables in real time based on the position of the mouse movement event. section SCSS
, we use these two CSS
variables to determine the position of the mouse tracking effect. By applying --x
and to the and attributes of --y
the pseudo-element , we can make the pseudo-element follow the mouse position. In addition, we also use variables to control the size of pseudo-elements. When the mouse hovers over the button, by changing the value, we can achieve a gradient background animation effect.::before
left
top
CSS
--size
--size
<template>
<div class="track-btn" @mousemove="handleMouseMove">
<span>使用 CSS 变量让你的按钮更炫酷</span>
</div>
</template>
<script>
export default {
methods: {
handleMouseMove(e) {
const btnStyle = e.target.style;
btnStyle.setProperty("--x", `${
e.offsetX}px`);
btnStyle.setProperty("--y", `${
e.offsetY}px`);
},
},
};
</script>
<style lang="scss">
.track-btn {
position: relative;
width: 400px;
height: 50px;
background-color: rgb(102, 219, 255);
cursor: pointer;
line-height: 50px;
text-align: center;
font-weight: bold;
font-size: 18px;
color: #fff;
overflow: hidden;
span {
position: relative;
pointer-events: none;
}
&::before {
--size: 0;
position: absolute;
left: var(--x);
top: var(--y);
width: var(--size);
height: var(--size);
background-image: radial-gradient(
circle closest-side,
rgb(0, 215, 82),
transparent
);
content: "";
transform: translate3d(-50%, -50%, 0);
transition: width 200ms ease, height 200ms ease;
}
&:hover::before {
--size: 400px;
}
}
</style>
- achieve effect
6. Variable scope
CSS
The scope of variables is the scope of the selector that defines them. Variables defined within a selector can only be used within that selector, while variables defined in the global scope can be used throughout the document.
1. Global scope
:root
Variables defined in pseudo-classes haveCSS
global scope;:root
Pseudo-class selectors match the root element of the document tree, usually<html>
the element;- Variables defined in
:root
pseudo-classes can be used globally throughout the document.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--bg-color: rgb(88, 88, 186);
--color: #33ca63;
}
div {
background-color: var(--bg-color);
color: var(--color);
}
span {
background-color: var(--bg-color);
color: var(--color);
}
</style>
</head>
<body>
<div>
<p>我在div内部</p>
</div>
<span>我在div外部</span>
</body>
</html>
- achieve effect
2. Local scope
- Variables defined inside a selector or element
CSS
have local scope; - These variables can only be used inside the selector or element in which they are defined;
- Variables in the local scope override variables with the same name in the global scope.
<!DOCTYPE html>
<html>
<head>
<style>
div {
--bg-color: rgb(88, 88, 186);
--color: #33ca63;
}
p {
background-color: var(--bg-color);
color: var(--color);
}
span {
background-color: var(--bg-color);
color: var(--color);
}
</style>
</head>
<body>
<div>
<p>我在div内部</p>
</div>
<span>我在div外部</span>
</body>
</html>
- achieve effect
3. Set scoped in vue
In , when you add the attribute vue
to the component's tag , the style will be scoped to the component. This means that only elements within the current component will be affected by these styles and will not leak to other components. However, the behavior of variables in styles is different from normal selector styles. When you use the attribute in a tag, a unique class name is automatically added to the root element of each component to ensure that the component's styles are only applied inside that component. Since the variable is global, its scope will exceed the scope of the component. So in a component with a style , variables are not effective in other components. In other words, you cannot use variables defined in one component in other components.<style>
scoped
CSS
CSS
vue
scoped
<style>
scoped
vue
CSS
scoped
vue
CSS
CSS
If you want to vue
share variables between components CSS
, there are two common methods:
- Use
CSS
preprocessors such asSass
orLess
, which can provide variable scoping and sharing capabilities; - Define
CSS
the variable in a global style (without usingscoped
the attribute) so it is shared across all components.
It should be noted that if you choose to CSS
define variables in a global style, please ensure that the naming of the variables is unique to avoid possible conflicts.
7. Variable priority
CSS
Variables CSS
have the same priority as other attributes, following CSS
cascading rules. Here is CSS
the general order of attribute priority (from highest to lowest):
!important
:!important
The style declared using has the highest priority and will override all other styles;- Inline styles: Styles defined directly
HTML
using the attribute on the elementstyle
have higher priority; ID
Selector:ID
Styles defined using selectors have higher priority;- Class selectors, attribute selectors and pseudo-class selectors: The styles defined by these selectors have medium priority;
- Element selectors and pseudo-element selectors: The styles defined by these selectors have lower priority;
- Inherited styles: Styles inherited from parent elements have the lowest priority.
When variables are involved CSS
, they have the same precedence as other selectors. If multiple identical CSS
variables are defined on the same element, the variables defined later will overwrite the previous variables. If the same variable is defined in different selectors CSS
, the selector precedence rules are followed. For example, if a variable is defined in an inline style CSS
, it will have higher priority and will override the same variable defined in other selectors. Likewise, if ID
a variable is defined in a selector CSS
, it will have higher priority and will override the same variable defined in other selectors.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--primary-color: blue;
}
.container {
--primary-color: red;
}
.box {
background-color: var(--primary-color);
width: 200px;
height: 200px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
In this case, we defined a variable called --primary-color
and CSS
set :root
it to blue in the pseudo-class. Then, .container
the same variable was redefined in the class selector and set to red. In .box
the class selector, we use var()
the function to reference --primary-color
the variable and use it as the background color. Since .container
the class selector has higher priority, the final .box
background color will be red.
- achieve effect
8. Compatibility
CSS
Variables actually have good compatibility in modern browsers, but there may be some limitations in some older versions of browsers.
Browser | compatibility |
---|---|
Chrome | Supports Chrome 49 versions from and above |
Firefox | Supports Firefox 31 versions from and above |
Safari | Supports Safari 9.1 versions from and above |
Opera | Supports Opera 36 versions from and above |
Edge | Supports Edge 15 versions from and above |
Internet Explorer | CSS Variables are not supported |
9. Improvements brought about by using CSS variables
-
Reusability and ease of maintenance
CSS
Variables allow you to define a style once and reuse it multiple times throughout the style sheet. This can reduce code duplication and improve code maintainability. By modifying the value of a variable, you can easily change the appearance of an entire style without having to modify each specific style individually. -
Dynamic and flexible
CSS
Variables can be modified dynamically at runtime without modifying the stylesheet. This makes it easier to apply different styles under different conditions. For example, you can achieve dynamic style changes by changing the value of a variable based on user selection or theme switching. -
Responsive design
CSS
Variables can be used in conjunction with media queries to achieve responsive design. By defining different variable values in different media queries, you can adjust styles based on the device's screen size and characteristics. This allows web pages to adapt to different screen sizes and device types, providing a better user experience. -
Readability and maintainability
CSS
Variables can be defined with meaningful names, making stylesheets easier to understand and maintain. Using variables makes your code more readable and makes the intent of the style clearer than hardcoding values or colors. -
global control
CSS
Global style control can be achieved by defining variables on the root element . This means you can use the same variables throughout your website, ensuring a consistent look and feel. If you need to change a style, you only need to modify the value of the variable without modifying each specific style one by one.