乐闻世界logo
搜索文章和话题

Nextjs 如何设置 image 组件的宽度为 100px ?

7 个月前提问
3 个月前修改
浏览次数209

6个答案

1
2
3
4
5
6

在 Next.js 的 next/image 组件中,通常我们不直接设置高度为100%,因为next/image组件是为了优化Web图片而设计的,它内部进行了很多优化处理,包括懒加载、图片压缩和各种尺寸的生成等。next/image 组件通常需要你提供图片的宽度和高度,以便能够生成不同尺寸的图片,以及保持图片的原始宽高比。

不过,如果你的设计需要让图片的高度适应其父元素的高度,可以通过几种方式来间接实现:

  1. 使用外部容器来控制尺寸: 你可以创建一个外部容器,并设置其高度为100%,然后将 next/image 组件放入其中,并使用layout="fill"属性,这样图片就会填充整个容器。
jsx
<div style={{ position: 'relative', height: '100%' }}> <Image src="/path/to/image.jpg" alt="描述文字" layout="fill" objectFit="cover" // 或者其它适合的object-fit值 /> </div>

在上述代码中,objectFit属性类似于CSS的object-fit,你可以设置为covercontainnone等值,根据图片与容器的关系,让图片以不同的方式填充容器。

  1. 使用样式覆盖: 你可以通过全局样式或者内联样式的方式,覆盖next/image组件的默认样式。但是这种方式可能会破坏next/image的一些内部优化,所以不太推荐使用。

例如:

css
/* 在全局样式文件中 */ .customImg { height: 100% !important; } /* 或者使用内联样式,需要注意的是,Next.js 不允许直接对 Image 组件使用内联样式,你可能需要通过其他方式如styled-jsx来实现 */

使用这种方法时,需要注意,直接改变next/image的高度可能会导致图片的宽高比失调,导致图片变形。

在实际项目中,推荐的方法是第一种,通过外部容器来控制图片的尺寸,这样能够更好地利用next/image组件的优化特性。如果必须要让图片的高度为100%,一定要注意图片的宽高比,确保图片不会因为尺寸调整而失真。

2024年6月29日 12:07 回复

这对我有用。

next/image

shell
<div style={{width: '100%', height: '100%', position: 'relative'}}> <Image alt='Mountains' src='/mountains.jpg' layout='fill' objectFit='contain' /> </div>

next/future/image

shell
<Image fill alt='Mountains' src='/mountains.jpg' sizes='100vw'/>

下一个/未来/图像

2024年6月29日 12:07 回复

在 NextJS 12 及更低版本中

shell
<Image src="/path/to/image.jpg" alt="" title="" width="100%" height="100%" layout="responsive" objectFit="contain"/>
2024年6月29日 12:07 回复

这是一种方法:例如,我想要一个覆盖其容器(div)的整个宽度和高度的图像。

shell
<div className={'image-container'}> <Image src={path} layout="fill" className={'image'} /> </div>

这是样式:(有一个容器 div 占据视口的一半宽度和高度,我的图像将覆盖它。)

shell
// Nested Styling .image-container { width: 50vw; height: 50vh; position: relative; .image { width: 100%; height: 100%; position: relative !important; object-fit: cover; // Optional } } // Or Normal Styling .image-container { width: 50vw; height: 50vh; position: relative; } .image-container .image { width: 100%; height: 100%; position: relative !important; object-fit: cover; // Optional }
2024年6月29日 12:07 回复

在NextJS的 v13 版本中

shell
<Image src={src} width={200} height={160} alt={alt} sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw" style={{ height: '100%', width: '100%' }} //The point is right there! //OR className='w-100 h-100' />
2024年6月29日 12:07 回复

你的答案