Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

TailwindCSS background image

Hello,

I want to add a background image to a div.

This works.

<div class="bg-[url('http://localhost:8000/images/players_light.jpg')]">

But this doesn't work.

<div class="bg-[url({{ asset('images/players_light.jpg') }})]"> // tested with ```'{{ ... }}'``` and without ```{{ ... }}```

Can you help me ?

Thanks a lot ;).

V

0 likes
10 replies
Tray2's avatar

What does the generated html look like?

1 like
vincent15000's avatar

@Tray2 Here is the generated HTML.

class="bg-[url('http://localhost:8000/images/players_light.jpg')]"

And when I load this URL in the browser, I see the image.

http://localhost:8000/images/players_light.jpg
vincent15000's avatar

@Tray2 Humm ... incredible ... I didn't change anything and suddenly it works.

Perhaps a cache problem with the browser, I don't know.

vincent15000's avatar

@Tray2 It's not solved, but now I can reproduce the problem.

If I first write this code and load the page, it works.

<div class="bg-[url('http://localhost:8000/images/players_light.jpg')]">

Then I replace the previous code with this one and it works fine too when I reload the page.

<div class="bg-[url('{{ asset('images/players_light.jpg') }}')]">

If I change once again the code with for example bg-red-100 and then I rewrite the code with the asset(), I don't see the image any more.

Snapey's avatar

@vincent15000 because when the classes are evaluated, blade is not being processed. Why not just do this;

<div class="bg-[url('/images/players_light.jpg')]">
1 like
vincent15000's avatar

@Snapey The idea is then to replace the text by a variable to be able to call the image path from the database for example.

I have tried what you suggest and it doesn't work.

TampaBayDave's avatar

@vincent15000 I had the same issue. I just ended up creating a manual path to the public/images directory. Not ideal, but got a deadline to meet! :-)

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

it doesn't work.

useful

What url is it trying to load? Look in browser network tools.

With your revised (dynamic) requirements, this will never work with tailwind arbitrary classes since the filename is not known until runtime so it cannot compile the correct css in advance.

You will have to forget tailwind for this and use the style tag

1 like
newbie360's avatar

Tailwind can't use dynamic classes, but you can use safelist in tailwind.config.js ,

just in your case can't do that, because the urls is dynamic come from database.

may be show a image in div, another div overlap on it then set opacity

1 like

Please or to participate in this conversation.