- Published on
How to Use Tailwind CSS with Next.js Image
- Authors
- Name
- Ripal & Zalak
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.
layout="fill"
with TailwindCSS
Using 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 haverelative
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 theImage
component.
width
and height
Instead of layout="fill"
Using 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>
)
}
fill
Property in Next.js 13+
Using 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
next/image
?
1. Why is my TailwindCSS class not applying to 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>
next/image
in Next.js 14?
3. How do I use TailwindCSS with In Next.js 14, use fill
instead of layout="fill"
and set objectFit
via style
.