how to use background image in nextjs with tailwind css

In this section we will see how to use Background Image in nextjs with tailwind css. For this section we will use nextjs 13 and next/image component.

Install Tailwind CSS In NextJS 13


Example 1

First you need to download any image and import in public directory then use tailwind class to set background image. You can also use next/image height and width props

import Image from 'next/image';

export default function Home() {
    return (
        <div className="relative h-screen">
            <div className="absolute inset-0">
                <Image
                    src="/background.jpg"
                    alt="background image"
                    fill
                />
            </div>
            <div className="relative z-10 flex flex-col items-center justify-center h-full">
                <h1 className='text-2xl font-bold text-gray-200'>Next JS 13 Background Image with Tailwind CSS </h1>
                <p className='mt-4 text-sm text-white'>lorem ipsom Next JS 13 Background Image with Tailwind CSS</p>
            </div>
        </div>
    );
}
background image in nextjs with tailwind css

background image in nextjs with tailwind css

Example 2

You can also set nextjs image height and width using tailwind css class.

import Image from 'next/image';

export default function Home() {
    return (
        <div className="relative max-w-xl h-80">
            <div className="absolute inset-0">
                <Image
                    src="/background.jpg"
                    alt="background image"
                    fill
                />
            </div>
            <div className="relative z-10 flex flex-col items-center justify-center h-full">
                <h1 className='text-2xl font-bold text-gray-200'>Next JS 13 Background Image with Tailwind CSS </h1>
                <p className='mt-4 text-sm text-white'>lorem ipsom Next JS 13 Background Image with Tailwind CSS</p>
            </div>
        </div>
    );
}


Example 3

Responsive background image nextjs 13 with tailwind.

import Image from 'next/image';

export default function Home() {
    return (
        <div className="relative w-full h-60 lg:max-w-2xl lg:h-80">
            <div className="absolute inset-0">
                <Image
                    src="/background.jpg"
                    alt="background image"
                    fill
                />
            </div>
            <div className="relative z-10 flex flex-col items-center justify-center h-full">
                <h1 className='text-2xl font-bold text-gray-200'>Next JS 13 Background Image with Tailwind CSS </h1>
                <p className='mt-4 text-sm text-white'>lorem ipsom Next JS 13 Background Image with Tailwind CSS</p>
            </div>
        </div>
    );
}