英文:
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:
<Image
src={'/images/Wordmark_Horizontal.png'}
width={83}
height={24}
alt="logo"
className="h-auto w-auto"
/>
答案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:
<div style={{ position: "relative", width: "250px", height: "100px" }}>
<Image src="/mongodb.jpg" alt="logo" layout="fill" objectFit="fill" />
</div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论