English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The var() function can be used as the value of any attribute of an element. The var() function cannot be used as an attribute name, a selector, or anything other than an attribute value. (This usually results in a syntax error or a value unrelated to the variable).
Define a name called "--main-bg-Define the "color" property, and then use the var() function to call the property:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Tutorial(oldtoolbag.com)</title> <style> :root { --main-bg-color: coral; } #div1 { background-color: var(--main-bg-color); padding: 5px; } #div2 { background-color: var(--main-bg-color); padding: 5px; } #div3 { background-color: var(--main-bg-color); padding: 5px; } </style> </head> <body> <h1>var() function</h1> <div id="div1">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> <br> <div id="div2">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> <br> <div id="div3">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> </body> </html>Test and see ‹/›
The var() function is used to insert custom property values. This method is very useful if a property value is used in multiple places.
Supported Versions: CSS3
The numbers in the table indicate the first browser version that supports the function.
function | |||||
---|---|---|---|---|---|
var() | 49.0 | 15.0 | 31.0 | 9.1 | 36.0 |
var(custom-property-name, value)
Value | Description |
---|---|
custom-property-name | Required. The name of the custom property, must start with -- Start with. |
value | Optional. Alternate values to use when the property does not exist. |
Use the var() function to call multiple custom values:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Basic Tutorial(oldtoolbag.com)</title> <style> :root { --main-bg-color: coral; --main-txt-color: blue; --main-padding: 15px; } #div1 { background-color: var(--main-bg-color); color: var(--main-txt-color); padding: var(--main-padding); } #div2 { background-color: var(--main-bg-color); color: var(--main-txt-color); padding: var(--main-padding); } #div3 { background-color: var(--main-bg-color); color: var(--main-txt-color); padding: var(--main-padding); } </style> </head> <body> <h1>var() function</h1> <div id="div1">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> <br> <div id="div2">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> <br> <div id="div3">Basic Tutorial oldtoolbag.com - Learn the basics, and you can go further!‹/div> </body> </html>Test and see ‹/›