How to use bg-[url(<?=$image->toFile()->url() ?>)] with tailwind?

Hi there,

I need to display profile pics into circles. Pretty classic and could be made with mask-image with Tailwind.

It should look like :

<div class="mask-radial-at-center mask-radial-from-100% bg-[url(/img/mountains.jpg)] ..."></div>

So here’s my code

<!-- event speaker and moderator (if any) !-->

            <?php $speakers = $event->speakers()->toStructure();?>

<?php if ($speakers->isnotempty()):?> 

<div class="flex flex-row gap-1">

<?php foreach ($speakers as $speaker):?>

<?php if($speaker->speakerPortrait()->toFile()):?>

<div class="mask-radial-at-center mask-radial-from-100% h-10 bg-[url(<?= $speaker->speakerPortrait()->toFile()->crop(200)->url()?>)]">

</div>

<?php endif ?>

<?php endforeach ?>

</div>

<?php endif ?>

The issue I have is that when Tailwind is compiled, it doesn’t see any value into bg-[url(?= …?>)] and so this isn’t compiled hence no image is shown.

So far when I was using this kind of bg, I was putting my images in a src folder to bypass this but for this case I can’t go that way.

I could try to use <img> instead and then add on top another div with the cercle, basically trying to recreate a mask..

Has anyone find out a solution to use Tailwind with dynamic images as background for div ?

Thanks for your help!

I found a trick. Declare a css var with <style> which isn’t parsed by Tailwind and add a custom css class in tailwind safelist.

So in my template :

<div style="--portrait-url: url('<?= $speaker->speakerPortrait()->toFile()->crop(200)->url()?>')" class="bg-portrait bg-cover bg-center mask-radial-at-center mask-radial-from-100% size-10"> </div>

and then in css file use @utility :

@import 'tailwindcss';

@plugin "@tailwindcss/typography";


@utility bg-portrait {

background-image: var(--portrait-url);

}

Hey @ImaCrea,

Glad you solved it yourself. Another approach for your toolbelt would be to set the background image with an inline style attribute:

<div class="your tailwind classes" style="background-image: url('$speaker->speakerPortrait()->toFile()->crop(200)->url()')"></div>

Best
Benedict

Thanks for this addition @benzin :slight_smile: