Published on

How to Use Background Image with Tailwind in Next.js

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Use Background Image with Tailwind in Next.js

If you are working with Next.js and Tailwind CSS and want to set a background image properly, you may run into issues if you try to import images directly. Below are the best ways to achieve this efficiently.

If your image is in the public folder, you don’t need to import it. Instead, reference it using a relative path.

✅ Correct Implementation:

export default function Home() {
  return <div className="h-[972px] bg-[url('/bg.png')] bg-scroll"></div>
}

This method ensures that Next.js serves the image correctly without additional processing.


Solution 2: Using Tailwind Configuration for Custom Backgrounds

You can also define custom background images in your tailwind.config.js file.

Step 1: Add the Image Path in tailwind.config.js

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

Step 2: Use the Custom Background Class in Your Component

export default function Home() {
  return <div className="bg-custom-bg h-[972px] bg-scroll"></div>
}

While this approach works, it’s not ideal in Next.js since it doesn’t optimize images.

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

FAQs

1. Why is my background image not showing in Next.js?

Ensure that:

  • The image is inside the public folder and is referenced correctly.
  • You are using Tailwind’s background utilities correctly (bg-[url('/bg.png')]).
  • If using tailwind.config.js, you restart the Next.js server after making changes.

2. Can I use Next.js Image component for background images?

No, the next/image component is meant for <img> elements and does not work for background images.

3. How do I make the background image responsive?

Use Tailwind’s responsive utilities:

<div className="h-screen bg-[url('/bg.png')] bg-cover bg-center md:bg-contain lg:bg-cover"></div>