Search code examples
frontendsveltesvelte-3

How to style element content in Svelte?


<style>

  color: red;

</style>

Some html content!

this code does not work. In the Angular framework it can be done by using the :host selector. :global can't help in my case, because I just want to style the component, where these styles are written. How can I do this in Svelte? Thank you

PS. I'm pretty new in Svelte :)


Solution

  • <style>
      .hello {
        color: red;
      }
    </style>
    
    <div class='hello'>Hello world</style>
    

    This will style all elements with the hello class and only in this component.

    Now if we do something like this

    App.svelte

    <script>
        import A from './A.svelte'
        import B from './B.svelte'
    </script>
    
    <div>
        <A/>
        <B/>
    </div>
    

    A.svelte

    Hello
    

    B.svelte

    world
    

    then svelte renders that as

    <div>Hello world</div>
    

    And there's no way to define a selector to style only "Hello" but not "word". The documentation also mentions that it need something to attach a class to:

    CSS inside a block will be scoped to that component.

    This works by adding a class to affected elements, which is based on a hash of the component styles (e.g. svelte-123xyz).