Search code examples
csssvelte

Linking css file with svelte component


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>`


Solution

  • You can import styles into a svelte component by simply using the css @import directive with the file name on it. Example:

    ...
    
    <h1>This is a title</h1>
    <p>More content</p>
    
    ...
    
    <style>
    @import './styles.css';
    </style>
    
    

    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.