如何在 Next.js 图像中使用 Tailwind CSS

Pra*_*nta 17 next.js tailwind-css nextjs-image

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

这是我的代码:

<Image
    src={img.img}
    alt="Picture of the author"
    width="200"
    height="200"
    className="bg-mint text-mint fill-current"
></Image>
Run Code Online (Sandbox Code Playgroud)

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

如果我不使用heightandwidth属性,这里是错误。 在此处输入图片说明

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

在此处输入图片说明

tja*_*son 30

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

  • 有没有办法通过其中的内容而不是图像的高度来确定高度? (2认同)

小智 5

它已经解决了,不再需要 hacky 解决方案。只需直接使用 Tailwind 来设计它们即可!

https://nextjs.org/blog/next-12-2