【问题标题】:如何将 Tailwind CSS 与 Next.js 图像一起使用
【发布时间】:2021-02-26 23:49:44
【问题描述】:

我正在尝试在 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>

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

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

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

【问题讨论】:

  • 与我们分享错误输出。
  • @JuanMarco 更新...

标签: next.js tailwind-css nextjs-image


【解决方案1】:

在 Next.js GitHub 项目中有一个 discussion and related example。听起来该示例实现了您想要做的事情。 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>

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

【讨论】:

  • 有没有办法通过里面的内容而不是图片的高度来确定高度?
【解决方案2】:

您可以使用 div 容器并向其应用类。

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

【讨论】:

    【解决方案3】:

    原因是 Image 组件在 DOM 上的挂载方式。如果你检查 DOM,你会看到这是一个 Image 组件:

    如您所见,next.js 围绕 img 创建了一个包装 div。所以要定位img,你实际上应该定位包装器div:

    还可以添加自定义类并调整css

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-15
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2021-09-07
      • 2020-09-18
      • 2021-08-22
      相关资源
      最近更新 更多