Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Tailwind CSS with Next.js Image

Tags:

I am trying to use Tailwind CSS in an Next.js project but I cant't use my Tailwind classes with Next.js Image component.

Here's my code:

<Image     src={img.img}     alt="Picture of the author"     width="200"     height="200"     className="bg-mint text-mint fill-current" ></Image> 

I want to use Tailwind classes instead of the height and width property of the Next.js Image. But I can't because it throws me an error. Also, unsized property throws another error saying it's deprecated. Is there any solution?

Here is the error if I don't use the height and width property. enter image description here

When I use the layout='fill' property it shows only one picture. And if I use the unsized property, then the following error is shown.

enter image description here

like image 301
Pranta Avatar asked Nov 15 '20 16:11

Pranta


People also ask

Where should I put my next js images?

Next. js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL ( / ). Note: next/image requires Next.

Does Tailwind CSS use JavaScript?

Tailwind CSS is written in JavaScript and distributed as an npm package, which means you've always had to have Node. js and npm installed to use it.

Can I use IMG tag in next js?

You can render images on your Next. js webpage without much hassle with the <img> tag, provided the image, if stored locally, is moved to the /public folder directory.


1 Answers

There’s a discussion and related example over at the Next.js GitHub project. It sounds like that example achieves what you want to do. tl;dr:

<div className="h-64 w-96 relative"> // "relative" is required; adjust sizes to your liking   <Image     src={img.img}     alt="Picture of the author"     layout="fill" // required     objectFit="cover" // change to suit your needs     className="rounded-full" // just an example   /> </div> 

The image will preserve its original aspect ratio and fill / cover (or whatever object-fit you chose) the size of the outer div, which you can set using Tailwind classes. Other styles, like rounded corner, can be applied to the Image.

like image 112
tjanson Avatar answered Sep 22 '22 09:09

tjanson