1

I am using React with Tailwind CSS and trying to set a background image for one div. However, the background image isn't showing despite setting the tailwind.config.js and saving the image in the right place.

Is there something I am missing which gets Tailwind to load background images properly?

Here is my tailwind.config.js including the image I want to load called "background.jpg"

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
      'background': "url('src/images/background.jpg')"
    },
  },
  plugins: [],
}

The Component (I have listed bg-background in the className):

        <div className="App">
          <div className="container px-2 py-2 min-w-full bg-background">
            <div className="flex h-screen bg-red">
            <div className="m-auto">
           <h1 className="text-5xl">Element Reference App</h1>
           </div>
           </div>
</div>
    </div>

The file structure:

enter image description here

Julius Goddard
  • 249
  • 1
  • 3
  • 15
  • 1
    `backgroundImage` property is added as an Object in the docs https://tailwindcss.com/docs/background-image Could it be the reason? – Ozgur Sar Sep 22 '22 at 10:27

2 Answers2

2

I think you need to put the background image file in the public directory of your project. Then you can use url('/background.jpg') in Tailwind.

That will also work when you build for production. I doubt if using the src directory will work after building, because it will probably not be in the production dist.

Gabe
  • 2,168
  • 2
  • 4
  • 16
0

The extend section in the tailwind.config.js is wrong. the Pictures must be exported as objects.

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
      'background': "url('src/images/background.jpg')"
    },
  },
  plugins: [],
}

Must be changed to

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {
     backgroundImage: { 'background': "url('/src/images/background.jpg')" }
    },
  },
  plugins: [],
}
Julius Goddard
  • 249
  • 1
  • 3
  • 15