Search code examples
tailwind-csssveltesvelte-3sveltekit

How to use Tailwind background-image in SvelteKit


https://tailwindcss.com/docs/background-image#arbitrary-values

this is how I want to use Tailwind bg-image feature. This does not work using SvelteKit next 160 and Tailwind 3.0.9.

Code:

<script>
  import globe from '$assets/bg/bg_globe2.png'
</script>

<div
    class={`flex flex-col bg-primary-dark h-64 overflow-hidden bg-no-repeat bg-[right_-14rem_bottom_-10rem] bg-[url('${globe}')]`}
>
  //children
</div>

the bg-[right_-14rem_bottom_-10rem] class works without problems, so I assume Tailwind has problem with Svelte file paths?

EDIT: output from console.log(globe) is src/assets/bg/bg_globe2.png.


Solution

  • ❌ Arbitrary values cannot be computed from dynamic values
    <div class="bg-{ userThemeColor }"></div>

    ✅ Use inline styles for truly dynamic or user-defined values
    <div style="background-color: { userThemeColor }"></div>

    https://v2.tailwindcss.com/docs/just-in-time-mode#arbitrary-value-support

    Tailwind needs to find the full text value in your code to be able to generate the utility classes.