I am trying to link css file with my svelte kit component. I used link element to link it but it did not work. If I made internal style the css style will be applied to the component but when I try to link the component with css file it did not work and the style did not apply
<svelte:head>
<link href="../style/index.css">
</svelte:head>
<h1>Welcome to your library project</h1>
<p>Create your package using @sveltejs/package and preview/showcase your work with SvelteKit</p>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>`
2
Answers
let see first we should know that Svelte has its own way of handling styles. It prefers encapsulated styles within the component itself using the tag. This makes sure that styles are scoped only to the component and don’t accidentally affect other parts of your app. does that make sense?
but if you want to link like an external CSS file to a Svelte component or globally, here’s how i would do it:
For SvelteKit (which it seems you’re using given that you mentioned of kit.svelte.dev):
You should add global styles to the src/app.html (or a similar root HTML file if the structure has changed). Add your stylesheet link there, which is the global root of your application.
some things to remember here,
Sometimes, browsers cache older versions of CSS. Ensure you’re not facing a caching issue by doing a hard reload or checking your site in an incognito/private window.
Hopefully you should be able to effectively link and apply global CSS to your Svelte (or SvelteKit) application if you follow these steps, let me know
You can import styles into a svelte component by simply using the css
@import
directive with the file name on it. Example:This is useful if you want to reuse some css for different component, but usually it’s better to isolate styles into their own component. And another alternative is using the
+layout.svelte
file and put the CSS there, and as long as all of your components are in the same layout, they will share that style.