Custom properties and var
Definition and purpose
Custom properties store reusable CSS values on elements. Their names start with two hyphens and are case-sensitive. Unregistered properties inherit by default, so a section can provide a value to its descendants without affecting neighboring sections.
Inherited accent
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } .panel { --accent: navy; } p { color: var(--accent, black); } </style> </head> <body> <section class="panel"> <p id="a">News</p> <p id="b">Updates</p> </section> <p id="c">Outside</p> </body></html>Only paragraphs inside the panel inherit the accent. Outside uses black.
Syntax and mental model
Declare --accent: navy inside a rule; consume it with color: var(--accent). The optional second argument supplies a fallback if the referenced property has the guaranteed-invalid value (for example, an undefined unregistered property). It is not a general type validator or a fallback for browsers lacking var().
Local override
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } .panel { --accent: navy; } #b { --accent: green; } p { color: var(--accent, black); } </style> </head> <body> <section class="panel"> <p id="a">News</p> <p id="b">Updates</p> </section> <p id="c">Outside</p> </body></html>The second paragraph supplies its own value.
Common mistakes
A name such as --Accent is not --accent. Use the full unit in a variable value; var(--size)px cannot assemble a length token.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Importance and inline styles, Color mixing and relative colors. Next lesson: Inheritance and invalid value behavior.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Custom properties and var — knowledge check
Five questions on custom properties and var.
Which name is a custom property?
Where is an unregistered value inherited from?
What does var(--gap, 4px) use if --gap is undefined?
Are --Gap and --gap identical?
Which value can directly supply a length?