From 16504d1f5203b6bada19d22175335791e880de16 Mon Sep 17 00:00:00 2001 From: Conduitry Date: Fri, 15 Sep 2023 19:34:49 -0400 Subject: [PATCH] docs: add FAQ about why you can't keep unused styles (#9193) --- documentation/docs/05-misc/01-faq.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/documentation/docs/05-misc/01-faq.md b/documentation/docs/05-misc/01-faq.md index dd55458647..a5c2330f46 100644 --- a/documentation/docs/05-misc/01-faq.md +++ b/documentation/docs/05-misc/01-faq.md @@ -131,6 +131,17 @@ If you need hash-based routing on the client side, check out [svelte-spa-router] You can see a [community-maintained list of routers on sveltesociety.dev](https://sveltesociety.dev/components#routers). +## Can I tell Svelte not to remove my unused styles? + +No. Svelte removes the styles from the component and warns you about them in order to prevent issues that would otherwise arise. + +Svelte's component style scoping works by generating a class unique to the given component, adding it to the relevant elements in the component that are under Svelte's control, and then adding it to each of the selectors in that component's styles. When the compiler can't see what elements a style selector applies to, there would be two bad options for keeping it: + +- If it keeps the selector and adds the scoping class to it, the selector will likely not match the expected elements in the component, and they definitely won't if they were created by a child component or `{@html ...}`. +- If it keeps the selector without adding the scoping class to it, the given style will become a global style, affecting your entire page. + +If you need to style something that Svelte can't identify at compile time, you will need to explicitly opt into global styles by using `:global(...)`. But also keep in mind that you can wrap `:global(...)` around only part of a selector. `.foo :global(.bar) { ... }` will style any `.bar` elements that appear within the component's `.foo` elements. As long as there's some parent element in the current component to start from, partially global selectors like this will almost always be able to get you what you want. + ## Is Svelte v2 still available? New features aren't being added to it, and bugs will probably only be fixed if they are extremely nasty or present some sort of security vulnerability.