Functional values and environment
Definition and purpose
CSS can consume values from HTML attributes, custom properties and user-agent environment variables. attr() reads an attribute on the element, var() reads a custom property and env() reads a browser-defined environment value. They have distinct substitution and fallback rules.
Decorative attribute text
<!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; } #a::after { content: attr(data-label); } </style> </head> <body> <div id="a" data-size="120px" data-label="Draft">Panel</div> <div id="b" data-size="oops">Other</div> </body></html>The pseudo-element adds a decorative label.
Syntax and mental model
Untyped attr(data-label) is commonly used with generated content. Typed attr(data-size type(<length>), 80px) parses a length and falls back for a missing or unparseable attribute. Guard newer typed attr with @supports and a separate ordinary declaration. env(safe-area-inset-top, 0px) reads a known safe-area value when available; fallback applies when the variable is unavailable, not when its defined value is zero.
Environment fallback
<!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; } #a { padding-top: env(bytemind-unknown-inset, 12px); } </style> </head> <body> <div id="a" data-size="120px" data-label="Draft">Panel</div> <div id="b" data-size="oops">Other</div> </body></html>The deliberately unknown variable uses its fallback.
Common mistakes
Do not place essential labels solely in generated content. Typed attr acceptance is not universal; do not use attribute-derived values as URLs, which are restricted by attr tainting.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Rounding, remainder and comparison. Next lesson: Intrinsic and extrinsic sizing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functional values and environment — knowledge check
Five questions on functional values and environment.
Which function reads an HTML attribute?
Which grammar parses only a length?
What happens to attr fallback when a length attribute is malformed?
Does env fallback replace a defined zero value?
What protects against unsupported typed attr syntax?