我有一张超宽图像,我将其用作横幅。它的定义高度和宽度为 2560x670,但下一个 js 将图像渲染为 1789 × 438 像素。如何将宽高比保持在 2560x670?并且仍然保持对象适合:覆盖?我本质上希望在更改视口宽度时,图像的左侧和右侧裁剪掉标题,并保持纵横比相同。请参阅 apple.com 获取示例。
使用 next js v 12
`
<div
className={`relative flex justify-center px-componentPaddingMobile sm:px-componentPadding
`}
>
{/*Background Images*/}
<div className={`${smallHeroBackground ? "hidden tablet:flex" : "relative w-[2560px] h-[670px]"}`}>
<Image
src={`https:${heroMainBackground.fields.file.url}`}
alt={heroMainBackground.fields.description}
objectFit="cover"
layout="fill"
priority
/>
</div>
</div>
`
我尝试将包装图像的容器设置为实际照片的宽度和高度,设置渲染英雄横幅组件的父级组件的 w 和 h,使用下一个图像中的尺寸,并使用状态来创建图像内的长宽比,并尝试对保存图像的 div 使用动态填充技巧来创建长宽比。
如果此属性未按您的预期工作,请在视图中使用
style="background-image: url('https:${heroMainBackground.fields.file.url}');"
并将 css 添加到不带任何 img 的 div 中:
div.myClassName {
background-size: cover;
background-origin: border-box;
background-position: center;
}
向您的 div 添加标题属性(以替换 alt={heroMainBackground.fields.description})和 aria-label 以实现可访问性