Introduction
CSS variables help you reuse colors, sizes, or other values easily. They make changing styles faster and keep your code neat.
Jump into concepts and practice - no test required
CSS variables help you reuse colors, sizes, or other values easily. They make changing styles faster and keep your code neat.
:root {
--main-color: #3498db;
}
.element {
color: var(--main-color);
}--main-color.var(--variable-name) to get the value of a variable.:root {
--primary-color: #ff6347;
}
button {
background-color: var(--primary-color);
}:root {
--font-size: 1.2rem;
}
p {
font-size: var(--font-size);
}:root {
--padding: 1rem;
}
.container {
padding: var(--padding);
}This example shows how CSS variables control background color, text color, and padding. Changing the variable values updates the whole page style easily.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>CSS Variables Example</title> <style> :root { --main-bg-color: #282c34; --main-text-color: #61dafb; --padding-size: 1.5rem; } body { background-color: var(--main-bg-color); color: var(--main-text-color); padding: var(--padding-size); font-family: Arial, sans-serif; } h1 { font-size: 2rem; } p { font-size: 1rem; } </style> </head> <body> <h1>Welcome to CSS Variables</h1> <p>Using variables makes styling easier and faster.</p> </body> </html>
CSS variables can be changed with JavaScript for dynamic styling.
Variables inside :root are global and can be used anywhere in your CSS.
Using variables reduces mistakes and saves time when updating styles.
CSS variables store reusable values like colors and sizes.
They make your CSS easier to maintain and update.
Using variables helps keep your website consistent and neat.
--main-color with the value #3498db?:root.:root { --main-color: #3498db; } which is correct. Others use wrong selectors or assignment operators.<div> in this CSS?:root { --bg-color: lightgreen; } div { background-color: var(--bg-color); }--bg-color is set to lightgreen in :root, making it global.div uses background-color: var(--bg-color); which applies the variable's value.:root { --text-color: blue } p { color: var(text-color); }--text-color is declared correctly except missing semicolon, but CSS allows last property without semicolon.var(), the variable name must include the double dashes --. Here it is missing.:root allows changing one value to update all uses.--main-color in :root and use var(--main-color) everywhere uses variables globally, making updates simple. Options B, C, and D are less efficient or more complex.