#how to reference imported image for background using tailwind arbitrary value

12 messages · Page 1 of 1 (latest)

still hearth
#

i'm brand new to astro and tailwind, i'm trying to import this image and use it for my background like this but nothing shows up.
i don't know if this is me not understanding astro or tailwind or both.

---
<section class="relative bg-[{mysticbannerImage.src}] bg-cover bg-center bg-no-repeat">```

i've tried it without `.src` as well. when i put the image in public dir and reference it like `bg-[url('/mystic-banner.jpg')]` it does work.
#

also this works <Image src={mysticbannerImage}.../> so i assume the import and how i'm referencing it works

gloomy hatch
#

There are a few problems here. If you wanted to use string interpolation you have to use backticks and the ${} syntax ( you are missing a $ symbol and you're using just plain double quotes). HOWEVER, this wouldn't work with tailwind, because the tailwind compiler has to be able to statically analyse the classes, so that wouldn't work. The third point is that when you pass an imported image to the astro Image component, astro calls a function getImage to actually generate the final image for you (the import alone doesn't do that). So you have to call that function yourself. There is an example in the docs of the getImage function that explains how to do exactly what you're trying to do https://docs.astro.build/en/reference/api-reference/#getimage

magic wren
#

just do bg-[url('/assets/mystic-banner.jpg')]

gloomy hatch
magic wren
#

ah right

gloomy hatch
#

For completeness sake: if you don't care about image optimisation you can put the image file in your /public folder and then you can reference it as bg-[url('/mystic-banner.jpg')]

still hearth
#

ok thanks i think that makes sense, i'd like to know how to use the optimized image so i'll try to get it working with getImage.

regarding the string interpolation, if the tailwind compiler was not an issue, are you saying i would need to do something like `bg-[${mysticbannerImage}]`

gloomy hatch
#

Yes, in your example above the string in your html would literally read bg-[{mysticbannerImage.src}] you would have to write class={'relative bg-[${mysticbannerImage}] ...'} (the straight tics are supposed to be backticks, because backtics interfer with discords formatting), but I would completely avoid that with tailwind, because it would only work by accident and in the case of a URL most likely not at all

#

an you would have to wrap your interpolated string in url()

still hearth
#

ok i get it now, the entire string assigned to class needs to be a backtick-enclosed template literal, itself enclosed in curly braces. i can't have a template literal inside a double-quoted string, which makes sense for sane parsing.

thanks so much for your help. really appreciated!