Variables in <style> tag?

Issue

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!

Solution

From my knowledge, I would use

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

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


<style>
    main {
        position: relative;
        background-image: var(--bg-img);
        ....
    }
    
    main::before {
        content: "";
        position: absolute; 
        width: 100px;
        height: 100px;
        background-image: var(--bg-img);
        ....
    }
</style>

Answered By – Adiat Hasan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published