Reputation: 87
I'm currently trying to use a dynamic background using multiple image size using tailwind with a template literal to no avail.
<div className={`bg-[url('../public${small}\')] md:bg-[url('../public${large}\')]` grid grid-cols-3 bg-cover shrink-0 w-60 ml-4 h-36 rounded-lg md:ml-2`}>
<div className=" visible col-span-2 self-end">
<div className='text-left ml-4 mb-2'>
<div className='movie-info opacity-70 align-middle text-xs font-light space-x-1 flex text-x-white'>
<p>{year}</p>
<span>•</span>
<div className='flex align-middle'>
<img
src="/assets/icon-category-movie.svg"
alt=""
className="w-3 mr-1"
/>
<span >{category}</span>
</div>
<span>•</span>
<p>{rating}</p>
</div>
<h1 className='text-base'>{title}</h1>
</div>
</div>
<div className="bg-x-mirage w-6 h-6 flex justify-center items-center rounded-full mr-4 my-2 mx-auto opacity-70 md:w-10 md:h-10 md:mt-3 md:mr-3">
<img
src="/assets/icon-bookmark-empty-new.svg"
alt=""
className="w-2 m-auto md:w-3"
/>
</div>
</div>
The line I have question about....
`bg-[url('../public${small}\')] md:bg-[url('../public${large}\')]...`
Before you suggest that I should use the style attribute, please note that the value passed in has to change based on the screen size. Ive read that arbitrary values cannot be computed from dynamic values. Is there any possible workaround?
Upvotes: 1
Views: 2714
Reputation: 19308
You can't dynamically generate classes with Tailwind. That code will never make it to your output CSS.
Rather than set your background image property inline, where you won't be able to swap responsively, use custom properties instead. Set custom properties for the small and large backgrounds in a style attribute and apply with an arbitrary value in Tailwind.
Example:
<div
className='bg-[image:var(--bg-small-url)] md:bg-[image:var(--bg-large-url)] restOfClasses...'
style={{
'var(--bg-small-url)': smallImageUrl,
'var(--bg-large-url)': largeImageUrl,
}}
>
Upvotes: 1