DEV Community

Cover image for How to use Tailwind CSS with Next.js Image
PRANTA Dutta
PRANTA Dutta

Posted on • Updated on

How to use Tailwind CSS with Next.js Image

Hello guys, hope you are doing well. In this post I am going to discuss how to properly use tailwindcss classes with next.js.

I don't know about you, but these days I am only using tailwindcss. I can't think of a better alternative to writing a bunch of css and css classnames (ugh...😒). Also, I have been using next.js as a react alternative in my workplace lately.

As you probably know, Next.js now supports image optimization. But in order to do that, we had to set the height and width of the image when defining the component.

  <Image
    src='/images/logo.png'
    alt="Logo"
    width="200"
    height="200"
    className="h-48 w-48 md:h-96 md:w-96" // this won't work
  />
Enter fullscreen mode Exit fullscreen mode

This works to an extent. But maybe you don't want that much height and width in the small screen. Next.js does some kind of optimization for you here, but maybe that's not enough. Maybe, you want to control the height and width of this image with tailwind classes. So how can we do that?

It turned out we can use a property called layout in the Image component and set it to layout="fill". Then we don't need to specify the height and width of that image.

Important

You need to set the parent of this image as relative because layout="fill" actually makes the image an absolute component.

So, the final code should look something like this.

  <div className="relative h-48 w-48 md:h-96 md:w-96"> //"relative" is required; change height and width if needed
    <Image
      src='/images/logo.png'
      alt="Logo"
      layout="fill" // required
      objectFit="cover" // change as you like
      className="rounded-full" // you can use other classes here too
    />
  </div>
Enter fullscreen mode Exit fullscreen mode

I really hope this helped you and feel free to comment if you want to know something else.
I have been Pranta and you have been excellent. Thanks 🥰.

Top comments (2)

Collapse
 
rahikif profile image
Rahik-IF

But brother, by this method the ring property of tailwind not working properly, unfortunately cropped!!

Collapse
 
pranta profile image
PRANTA Dutta

Actually you might not even need to use another div with images anymore, check out the latest version documentation of Next.js. Right now, you can fix that by giving the ring class to the wrapping div.