使用Next Image组件保持图像的宽高比

huangapple go评论62阅读模式
英文:

Preserving aspect ratio of image with Next Image component

问题

我正在使用Next的Image组件来加载一个徽标。该图像的尺寸为1843x550像素,但我正在使用宽度和高度属性将图像的大小调整为需要的83x24像素。由于我使用的纵横比略有不同,因此我收到了以下警告:

> 图像的src属性为"/images/Wordmark_Horizontal.png",但宽度或高度已被修改,而另一个属性没有修改。如果您使用CSS更改图像的大小,请同时包括样式'width: "auto"'或'height: "auto"'以保持纵横比。

问题在于当我将宽度和高度都设置为CSS的auto时,我的图像变成了128x38像素,比我需要的大。

首先,为什么图像的尺寸会被调整为我没有指定的尺寸?我需要采取什么措施既保持图像的纵横比,同时又使其保持适当的大小?

我的代码如下:

<Image
	src={'/images/Wordmark_Horizontal.png'}
	width={83}
	height={24}
	alt={'logo'}
	className={'h-auto w-auto'}
/>
英文:

I'm using Next's Image component to load up a logo. The image is 1843x550 px, but I'm using the width and height properties to size the image for the space it needs to be, which is 83x24 px. Because the aspect ratio I'm using is slightly different, I'm getting the warning:
>Image with src "/images/Wordmark_Horizontal.png" has either width or height modified, but not the other. If you use CSS to change the size of your image, also include the styles 'width: "auto"' or 'height: "auto"' to maintain the aspect ratio.

The issue is that when I set both width and height to auto with css, my image becomes 128x38 px, larger than I need.

First, why is the image sized to a dimension that I haven't specified? What do I need to do to both preserve the aspect ratio of the image, while also keeping it sized appropriately?

My code:

&lt;Image
	src={&#39;/images/Wordmark_Horizontal.png&#39;}
	width={83}
	height={24}
	alt=&quot;logo&quot;
	className=&quot;h-auto w-auto&quot;
/&gt;

答案1

得分: 1

你可以尝试在父容器上使用“relative”定位:

<div style={{ position: "relative", width: "250px", height: "100px" }}>
  <Image src="/mongodb.jpg" alt="logo" layout="fill" objectFit="fill" />
</div>
英文:

You can try this using relative positioning for parent container:

&lt;div style={{ position: &quot;relative&quot;, width: &quot;250px&quot;, height: &quot;100px&quot; }}&gt;
  &lt;Image src=&quot;/mongodb.jpg&quot; alt=&quot;logo&quot; layout=&quot;fill&quot; objectFit=&quot;fill&quot; /&gt;
&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年7月11日 03:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定