skip to Main Content

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


  1. 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:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/style/index.css">
    <!-- ... other head elements ... -->
    </head>
    <body>
    <script type="module" src="/build/bundle.js"></script>
    </body>
    </html>
    

    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,

    1. Make sure the path is correct
    2. make sure that the CSS file is being served
    3. Check for caching issues:

    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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search