Published on

How to Use Tailwind CSS with Next.js Image

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Use Tailwind CSS with Next.js Image

Tailwind CSS and Next.js Image components can work together seamlessly, but applying Tailwind classes directly to next/image might not always work as expected. Here's how to style the Next.js Image component using Tailwind CSS.

Using layout="fill" with TailwindCSS

The best approach is to wrap the Image component in a div with relative positioning.

import Image from 'next/image'

export default function MyComponent() {
  return (
    <div className="relative h-64 w-96">
      {' '}
      {/* Adjust width and height as needed */}
      <Image
        src="/example.jpg"
        alt="Example Image"
        layout="fill"
        objectFit="cover"
        className="rounded-lg"
      />
    </div>
  )
}

Explanation:

  • The div acts as a container and must have relative positioning.
  • layout="fill" makes the image fill its parent.
  • objectFit="cover" ensures the image maintains aspect ratio while covering the container.
  • Tailwind classes like rounded-lg can be applied to the Image component.

Using width and height Instead of layout="fill"

If you want to specify the width and height explicitly, do this:

import Image from 'next/image'

export default function MyComponent() {
  return (
    <div className="flex justify-center bg-gray-200 p-4">
      <Image
        src="/example.jpg"
        alt="Example Image"
        width={200}
        height={200}
        className="rounded-full border-2 border-gray-500"
      />
    </div>
  )
}

Using fill Property in Next.js 13+

Since Next.js 13, objectFit is no longer directly supported. Instead, you must pass it as a style property:

<Image
  src="/example.jpg"
  alt="Example Image"
  fill={true}
  style={{ objectFit: 'cover' }}
  className="rounded-lg"
/>

FAQs

1. Why is my TailwindCSS class not applying to next/image?

Next.js optimizes images, which may prevent some Tailwind classes from working directly. Wrap the Image component inside a div and apply styles there.

2. How do I make a responsive image using Tailwind?

Use a wrapper with relative and layout="fill" for responsiveness:

<div className="relative h-64 w-full">
  <Image src="/example.jpg" alt="Responsive Image" layout="fill" objectFit="cover" />
</div>

3. How do I use TailwindCSS with next/image in Next.js 14?

In Next.js 14, use fill instead of layout="fill" and set objectFit via style.