Search code examples
javascriptstylessvelte

Svelte dynamic style handling


https://svelte.dev/repl/83031a6a492c4a30a861e4310209e9b6?version=3.24.0

Is there another approach instead of writing style direct into the raw style tag?:

<div style="width: {width}; height: {height};">ᕕ( ᐛ )ᕗ</div>

Or; what is best practice in such cases, where the delivered style could be anything / is dynamic, and not preclassable?


Solution

  • Here is one example:

    <script>
      let bgcol="blue"
      let style=`color:red;background-color:${bgcol}`
    </script>  
        ​
    <h1 {style}> Hello <h1>
    

    EDIT: {style} is shorthand for style={style}

    You can find working example from REPL:

    https://svelte.dev/repl/f039834923014cd7aca30c54d957c844?version=3.24.0