Julius Goddard
Julius Goddard

Reputation: 347

Tailwind CSS does not load Background Images in React App

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

Upvotes: 1

Views: 6129

Answers (3)

shahriarpshuvo
shahriarpshuvo

Reputation: 464

To answer @MrPatel2021, question above:

but what when background-image comes from API? How can I set API response in tailwind config file?

To achieve this, you need to do it inline:

<div className="bg-[url('path-to-your-remote-image.png')]">
  <!-- ... -->
</div>

Use tailwind-merge (recommended) or clsx lib to merge or join other class names.

Upvotes: 0

Gabe
Gabe

Reputation: 2636

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.

Upvotes: 3

Julius Goddard
Julius Goddard

Reputation: 347

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: [],
}

Upvotes: 0

Related Questions