0

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.