Consider this Svelte component using CSS variables. What color will the text inside the <p> tag be?
<script> let themeColor = 'blue'; </script> <style> :root { --main-color: red; } p { color: var(--main-color); } .dynamic { --main-color: {themeColor}; } </style> <div class="dynamic"> <p>Hello world!</p> </div>
Remember that CSS custom properties cascade and can be overridden by classes on parent elements.
The .dynamic class attempts to set --main-color to the value of the themeColor variable, which is 'blue'. However, CSS inside the <style> block cannot interpolate Svelte variables directly. To apply dynamic CSS variables, inline styles or reactive style attributes should be used. In this code, the CSS variable --main-color remains 'red' from :root, so the text color will be red.
Which option correctly defines and uses a CSS custom property inside a Svelte <style> block?
CSS custom properties start with two dashes and use var(--property-name) to access.
Option A correctly defines the custom property with --bg-color: green; and uses var(--bg-color) to apply it. Other options have syntax errors or misuse the variable.
Given this Svelte component, what background color will the <div> have after clicking the button once?
<script> let color = 'red'; function changeColor() { color = 'green'; } </script> <style> div { background-color: var(--bg-color, blue); width: 100px; height: 100px; } </style> <div style="--bg-color: {color}"></div> <button on:click={changeColor}>Change Color</button>
Inline styles with CSS variables can update reactively when bound to Svelte variables.
The <div> initially has --bg-color set to 'red' from the color variable. Clicking the button changes color to 'green', updating the inline style and changing the background color to green.
Look at this Svelte component. Why does the text color not change to green?
<script> let textColor = 'green'; </script> <style> p { color: var(--text-color); } </style> <p style="text-color: {textColor}">Hello!</p>
Check if the CSS variable --text-color is actually set anywhere.
The CSS variable --text-color is used in the CSS but never defined. The inline style sets text-color, which is not a CSS property and does not define the variable. So the variable is undefined and the color does not change.
Which statement best explains why CSS custom properties are useful for theming in Svelte applications?
Think about how CSS variables can be changed dynamically and cascade through the DOM.
CSS custom properties can be updated dynamically via JavaScript or reactive frameworks like Svelte. This allows changing themes by updating variables at runtime without recompiling or reloading, making them ideal for theming.