How to use background image with tailwind in next.js?

Viewed 2060

I have a background image in the public folder named bg.png

In the index.js page of the pages folder I want to use that image as a background image

I have install tailwind following the documentation of their official website.

I have already tried this, but it doesn't work.

import BG from "../public/bg.png";

return (
  <div
    className="bg-scroll"
    style={{
      backgroundImage: `url(${BG})`,
      height: "972px",
    }}
  >
  </div>
)

It doesn't show the image.

3 Answers

Another way is that you can define the image in tailwind.config.js file as lke this

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      backgroundImage: {
        'my_bg_image' : "url('../public/bg.png')",
      }
    },
  },
  plugins: [],
}

Then use it in the component as bg-my_bg_img directly. No need to import image.

return (
  <div
    className="bg-scroll bg-my_bg_image h-[972px]"
  >
  </div>
)

When you have assets in a public folder no need to define all the exact path.

  <div
   className="bg-scroll"
   style={{
    backgroundImage: `url('/bg.png')`,
     height: "972px",
    }}
  >
</div>

Here is how you can do it all with Tailwind. You don't need to import the image either.

return (
  <div
    className="bg-scroll bg-[url('/bg.png')] h-[972px]"
  >
  </div>
)
Related