skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. Try remove thing quotes from url in the config.js

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

    Also if you are using next.js or vite-app, you might wanna use the public folder for images

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search