Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 installed 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.

like image 371
Nasem Avatar asked Jan 24 '26 06:01

Nasem


2 Answers

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>
like image 125
Paiman Rasoli Avatar answered Jan 25 '26 20:01

Paiman Rasoli


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>
)
like image 38
Mohit Maroliya B17CS036 Avatar answered Jan 25 '26 22:01

Mohit Maroliya B17CS036



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!