Consider this Svelte component that uses a <style> tag with a dynamic CSS variable:
<script>
export let color = 'blue';
</script>
<style>
div {
color: var(--text-color);
}
</style>
<div style="--text-color: {color};">Hello</div>What color will the text inside the <div> be when rendered?
<script> export let color = 'blue'; </script> <style> div { color: var(--text-color); } </style> <div style="--text-color: {color};">Hello</div>
Look at how the CSS variable --text-color is set inline on the div.
The inline style sets the CSS variable --text-color to the value of the color prop, which defaults to 'blue'. The CSS uses this variable for the text color, so the text appears blue.
You want to apply a dynamic background color to a <button> using CSS-in-JS in Svelte. Which code snippet correctly does this?
Remember how to insert JavaScript variables inside Svelte attribute bindings.
In Svelte, to use a JavaScript variable inside an attribute, you wrap it in curly braces. So {bgColor} correctly inserts the variable's value. The other options either treat it as a string or use invalid syntax.
Given this Svelte component:
<script>
let color = 'green';
</script>
<style>
.text {
color: color;
}
</style>
<p class="text">Hello</p>Why is the text color not green?
<script> let color = 'green'; </script> <style> .text { color: color; } </style> <p class="text">Hello</p>
Think about how CSS and JavaScript variables interact in Svelte.
CSS inside <style> tags cannot access JavaScript variables directly. The word 'color' in CSS is treated as a literal color name, which is invalid here. To use dynamic colors, you must use inline styles or CSS variables.
Consider this Svelte component:
<script>
import { writable } from 'svelte/store';
const bg = writable('white');
function toggle() {
bg.update(c => c === 'white' ? 'black' : 'white');
}
</script>
<button on:click={toggle} style="background-color: {$bg};">Toggle</button>What is the background color of the button after clicking it twice?
<script> import { writable } from 'svelte/store'; const bg = writable('white'); function toggle() { bg.update(c => c === 'white' ? 'black' : 'white'); } </script> <button on:click={toggle} style="background-color: {$bg};">Toggle</button>
Each click toggles the color between white and black.
Starting color is white. First click changes it to black. Second click changes it back to white.
Choose the statement that correctly explains a limitation or difference of CSS-in-JS in Svelte compared to React frameworks.
Think about how Svelte compiles components and handles styles differently from React.
Svelte compiles components to efficient JavaScript and CSS. It does not use a virtual DOM or runtime style injection like React. Therefore, popular React CSS-in-JS libraries like styled-components do not work out of the box. Instead, Svelte encourages scoped styles in <style> tags and dynamic styling via inline styles or CSS variables.