Consider two Svelte components, Parent.svelte and Child.svelte. Parent.svelte has a <style> block defining p { color: red; }. If Parent renders Child, what color will the paragraph text inside Child be?
<!-- Parent.svelte -->
<p>This is parent text.</p>
<Child />
<style>
p { color: red; }
</style>
<!-- Child.svelte -->
<p>This is child text.</p>Think about how Svelte applies styles only to the component they are declared in.
Svelte scopes styles by default. The p { color: red; } style in Parent.svelte applies only to its own p elements. The paragraph text inside Child.svelte uses the default color because the parent's styles do not leak into child components.
Which of the following <style> blocks in a Svelte component will scope styles only to that component?
In Svelte, styles are scoped by default without extra attributes.
In Svelte, the plain <style> block automatically scopes styles to the component. Adding global makes styles global. The scoped attribute is not valid in Svelte. The module attribute is for CSS modules, which is a different feature.
Given this Svelte component, why does the h1 style affect elements outside this component?
<style global>
h1 { color: green; }
</style>
<h1>Title</h1>Check the effect of the global attribute on styles.
The global attribute on the <style> block disables scoping and applies styles globally. This causes the h1 style to affect all h1 elements in the app, not just inside this component.
In this Svelte component, what color will the paragraph text be after clicking the button once?
<script> let active = false; function toggle() { active = !active; } </script> <p class:highlight={active}>Hello!</p> <button on:click={toggle}>Toggle</button> <style> p { color: black; } .highlight { color: orange; } </style>
Consider how the class directive class:highlight works with the active variable.
Initially, active is false, so the highlight class is not applied. After clicking the button once, active becomes true, adding the highlight class. This changes the paragraph color to orange as defined in the scoped styles.
Which mechanism does Svelte use internally to scope styles to components by default?
Think about how Svelte compiles components and applies styles.
Svelte compiles components by adding unique attributes to elements and matching CSS selectors with those attributes. This ensures styles apply only to elements in that component without runtime overhead or iframes.