如何在 Next.js 图像中使用 Tailwind CSS [英] How to use Tailwind CSS with Next.js Image

查看:91
本文介绍了如何在 Next.js 图像中使用 Tailwind CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Next.js 项目中使用 Tailwind CSS,但我无法将 Tailwind 类与 Next.js Image 组件一起使用.

这是我的代码:

我想使用 Tailwind 类而不是 Next.js 图像的 heightwidth 属性.但我不能,因为它给我一个错误.此外, unsized 属性会引发另一个错误,指出它已被弃用.有什么解决办法吗?

如果我不使用 heightwidth 属性,则会出现错误.

当我使用 layout='fill' 属性时,它只显示一张图片.如果我使用 unsized 属性,则会显示以下错误.

解决方案

有一个 讨论和相关示例 在 Next.js GitHub 项目中.听起来这个例子实现了你想要做的事情.tl;博士:

//相对"是必须的;根据您的喜好调整尺寸<图像src={img.img}alt=作者的图片";布局=填充"//必需的objectFit=封面"//更改以满足您的需求className =四舍五入";//只是一个例子/>

图像将保留其原始纵横比并填充/覆盖(或您选择的任何object-fit)外部div的大小,您可以使用顺风课.其他样式,如圆角,可以应用于Image.

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.

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.

解决方案

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.

这篇关于如何在 Next.js 图像中使用 Tailwind CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆