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
What does the generated html look like?
@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
@Tray2 Humm ... incredible ... I didn't change anything and suddenly it works.
Perhaps a cache problem with the browser, I don't know.
@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.
@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')]">
@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.
@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! :-)
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
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
Please sign in or create an account to participate in this conversation.