Home > Net >  Variables in <style> tag?
Variables in <style> tag?

Time:09-27

Is it possible to have variables in the tag of a component with SvelteKit? For example I can get this to work:

<div class="mainContent" style="background-image: url('{backgroundImage}');">

But the following doesnt:

<style>
    main {
        background-image: url('{backgroundImage}');
        height: 85vh;
    }
</style>

Is it possible to get the latter to work? I ask because I want to be able to set a :before on that background image, which I don't velieve can be done inline.

Thanks!

CodePudding user response:

You can use css property(variable) as

<style>
    main {
        background-image: var(--backgroundImage);
        height: 85vh;
    }
</style>

then you can set value to this property dynamically using javascript as

document.documentElement.style.setProperty(
          "--backgroundImage",
          "url(myimage.png)"
        );

CodePudding user response:

From my knowledge, I would use

let backgroundImage = '..../../'

<div class="mainContent" style="--bg-img: url({backgroundImage})">


<style>
    main {
        background-image: var(--bg-img);
        ....
    }
</style>

  • Related