Consider a Svelte app with a global style defined in app.css and imported in App.svelte. How will the global style affect nested components?
/* app.css */ body { background-color: lightblue; } /* App.svelte */ <script> import './app.css'; import Child from './Child.svelte'; </script> <main> <Child /> </main>
Think about how CSS works in the browser and how Svelte handles style imports.
Global CSS files imported in a root component apply styles globally to the entire app, including nested components, because CSS cascades through the DOM.
In Svelte, how do you write a style block that applies styles globally instead of scoping them to the component?
<script> // No script needed </script> <style> /* Your style here */ </style>
Remember the special attribute Svelte uses to mark global styles inside a component.
In Svelte, adding the global attribute to the <style> tag makes the styles global instead of scoped.
Given the following Svelte component, why does the button not get the red background as expected?
<style>
button {
background-color: red;
}
</style>
<button>Click me</button>Think about how Svelte scopes styles and how that affects native elements inside the component.
The style is scoped to the component, so it applies to the button inside it. The button is styled red as expected. The question is tricky because the style is not global but still applies locally.
In a Svelte app, a global style toggles a class on the body element. What background color will the page have after toggling?
<script> let darkMode = false; function toggle() { darkMode = !darkMode; if (darkMode) { document.body.classList.add('dark'); } else { document.body.classList.remove('dark'); } } </script> <button on:click={toggle}>Toggle Dark Mode</button> <style global> body { background-color: white; } body.dark { background-color: black; } </style>
Consider how global styles and DOM class manipulation work together.
The global style defines background colors for body and body.dark. Toggling the dark class on body switches the background color accordingly.
:global() selector inside scoped styles in Svelte?What is the purpose of using the :global() CSS selector inside a scoped style block in Svelte?
<style>
:global(h1) {
color: green;
}
p {
color: blue;
}
</style>Think about how :global() overrides Svelte's default style scoping.
The :global() selector tells Svelte to apply the style globally, ignoring the component's scoped style rules. Other styles remain scoped.