使用CSS设置Next.js图片组件的宽度和高度

3

我正在使用Next.js提供的Image组件,但是它强制我将宽度和高度设置为固定值。我正在使用Tailwind CSS,并使用其实用程序类来设置图像的高度和宽度。

在此输入图片描述

<Image
      src={imageSrc}
      alt={name}
      className="object-cover object-center"
      layout="fill"
/>

有效的HTML和CSS代码如下:

enter image description here

<img
    className="w-auto h-6 lg:block"
    src="/img/logo-dark.png"
    alt="nftHODL.club Logo"
/>
2个回答

4

在具有尺寸和相对类的包装 div 中添加,并在 Image 组件上设置 layout="fill" 应该能够解决问题。

示例:

<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>

来源:https://techinplanet.com/how-to-use-tailwind-css-with-next-js-image/

本文介绍了如何在Next.js应用程序中使用Tailwind CSS样式,并展示了如何将Tailwind的样式应用到Next.js中的图片组件。


0
如果图像未从网络源加载(因此在创建捆绑包时已知其大小),则执行此操作更简单:
import YourImage from '../your/assets/image.png'
import styles from '../your/image.module.css'

<Image
  src={YourImage}
  alt='This is an image'
  className={styles.image}
/>

并在CSS文件中指定大小和其他属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接