Home > other >  How to use CSS from JS variable in Svelte?
How to use CSS from JS variable in Svelte?

Time:01-02

Please check a Svelte component below:

<script>
    import CodeViewer from '$lib/CodeViewer.svelte';

    const code = `       .ezy-rotate-180 {
            transition: 0.5s, color 0.1s;
            -webkit-transition: 0.5s, color 0.1s;
            -moz-transition: 0.5s, color 0.1s;
        }
        .ezy-rotate-180:hover {
            transform: rotate(180deg);
            -webkit-transform: rotate(180deg);
            -moz-transform: rotate(180deg);
        }`;
    const language = 'css';
</script>

<div >
    <div >
                    <!-- 1. added CSS class here
                             ↓   -->
            <div >Rotate 180</div>
    </div>

    <CodeViewer {code} {language} />
</div>

<style>
    {code} /* <== 2. I tried this, but not working */
</style>

In this component, I have CSS in a JS variable. I want apply the same CSS to a div and show it to through CodeViewer component. CodeViewer is working as expected.

But how I can apply that CSS (from JS variable) to a div?

CodePudding user response:

You cannot use interpolations in the <style> element. You can apply style properties via the style attribute on elements but not CSS rules.

For something like this you could programmatically create a style element in onMount which then can be updated when the code changes, something like:

let style;

onMount(() => {
    style = document.createElement('style');
    document.head.append(style);
    
    return () => style.remove(); // Cleanup on destroy
});

$: if (style) style.textContent = code;

REPL

  • Related