How do you declare a CSS variable and use it with a fallback value?

Study for the CSS Mastery Test. Boost your knowledge with flashcards and multiple-choice questions, featuring hints and explanations. Prepare effectively for your exam!

Multiple Choice

How do you declare a CSS variable and use it with a fallback value?

Explanation:
Using CSS custom properties means you declare a variable with a name that starts with two dashes and assign it inside a style rule using a colon. To use that variable and ensure a color even if the variable isn’t defined, you wrap the reference in the var() function and provide a second argument as the fallback value. A typical pattern is to declare the variable on a global scope like :root, then reference it with a fallback in the property you’re setting. For example: :root { --brand-color: #3366cc; } element { color: var(--brand-color, #000); } This sets the element’s color to the declared brand color. If, for any reason, --brand-color isn’t defined, the color will fall back to #000. The declaration must use a colon (not equals), and the fallback is specified as the second argument to var().

Using CSS custom properties means you declare a variable with a name that starts with two dashes and assign it inside a style rule using a colon. To use that variable and ensure a color even if the variable isn’t defined, you wrap the reference in the var() function and provide a second argument as the fallback value. A typical pattern is to declare the variable on a global scope like :root, then reference it with a fallback in the property you’re setting.

For example:

:root { --brand-color: #3366cc; } element { color: var(--brand-color, #000); }

This sets the element’s color to the declared brand color. If, for any reason, --brand-color isn’t defined, the color will fall back to #000. The declaration must use a colon (not equals), and the fallback is specified as the second argument to var().

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy