Search code examples
reactjspathtailwind-css

TailwindCSS background image not showing up (even in local env)


Currently using tailwindcss v3.3.5 and vite v5.0.0.

I have followed the official tailwind docs on how to configure background image in tailwind.config.js file, but am unable to get the background image to appear on my element.

My project folder structure:

root
|-- tailwind.config.js
|-- src
     |-- global.css
     |-- assets
          |-- images
               |-- bg-image.svg
     |-- components
          |-- folder
               |-- Component.tsx

My tailwind.config.js file:

theme: {
  extend: {
    backgroundImage: {
      "test-img": "url('./assets/images/bg-image.svg')",
    }
  }
}

And my Component.tsx, in which has a <form> element with width, height and a contrasting background-color set:

<form classname="bg-test-img other-styles"></form>

Not too sure exactly where is going wrong, my only guess is that the url() is wrong. In the code above, the url used is relative to global.css because I've read from somewhere that it resolves the issue (but not the case for me). I have also tried the path relative to tailwind.config.js:

"test-img": "url('./src/assets/images/bg-image.svg')"

but to no avail as well.

Edit: I have also tried removing the single-quotes in url() but that does not work also. Using arbitrary values doesn't work either.

<form classname="bg-[url('../../assets/images/bg-image.svg')] other-styles"></form>

I tried importing the svg to be used as the src for an <img/> element and it works, if this is relevant.


Solution

  • From Muhammad Faisal's answer, I discovered that the problem lies with placing the images under the src folder. I shifted everything into the public folder, changed the url to as such in tailwind.config.file:

    "test-img": "url('/images/bg-image.svg')"
    

    And everything works like a charm.