Harinder Singh
Harinder Singh

Reputation: 452

How to use CSS from JS variable in Svelte?

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 class="flex flex-row flex-wrap w-full">
    <div class="w-1/2">
                    <!-- 1. added CSS class here
                             ↓   -->
            <div class="ezy-rotate-180 px-10 py-2 bg-slate-50 text-black w-28 text-center rounded-md">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?

Upvotes: 0

Views: 429

Answers (1)

brunnerh
brunnerh

Reputation: 184376

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

Upvotes: 3

Related Questions