728x90
SMALL
#css
CSS Variables
You can create and use variables in CSS. Variables allow you to change multiple values at once.
Variable declaration
--variable-name: value;
When you define a variable, you can use it in the element that defined the variable and its child elements. To make it available everywhere: Define as root.
Use of variables
property: var( --variable-name )
example
Basic
Use the variable --my-color-1 set to red.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS</title>
<style>
:root {
--my-color-1: red;
}
.x {
color: var( --my-color-1 );
}
</style>
</head>
<body>
<h1 class="x">Lorem Ipsum Dolor</h1>
</body>
</html>
Undefined variable
Using an undefined variable has the same effect as not using that attribute.
<style>
:root {
--my-color-1: red;
}
.x {
color: var( --my-color-2 );
}
</style>
- You can specify a value to use when the variable is not defined.
- Orange is used because --my-color-2 is not defined.
<style>
:root {
--my-color-1: red;
}
.x {
color: var( --my-color-2, orange );
}
</style>
Variable declaration to a specific selector
- Declaring a variable in a particular selector allows you to use the variable in the element to which that selector applies and its child elements.
- --my-color-1 defined in .x cannot be used in .y.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS</title>
<style>
.x {
--my-color-1: red;
}
.x span {
color: var( --my-color-1 );
}
.y {
color: var( --my-color-1 );
}
</style>
</head>
<body>
<h1 class="x"><span>Lorem Ipsum Dolor</span></h1>
<h1 class="y">Lorem Ipsum Dolor</h1>
</body>
</html>
Browser support
Using CSS variables is a nice feature, but some browsers don't support it. In particular IE does not support 11 either.
728x90
LIST
'CSS' 카테고리의 다른 글
[CSS] CSS / Selector / Type Selector (0) | 2022.07.29 |
---|---|
[CSS] CSS / Selector / Universal Selector (0) | 2022.07.29 |
[CSS] CSS / inheritance (0) | 2022.07.29 |
[CSS] CSS / Basics /! Important (0) | 2022.07.28 |
[CSS] CSS / Basics / Grammar (0) | 2022.07.27 |