如何实现类似Nike的右侧裁剪式响应式Hero图片?
实现类似Nike官网的响应式Hero图片效果
需求说明:
- 创建响应式Hero图片,屏幕缩小时裁剪图片右侧,保持固定高度与位置
- 保留图片原有左右留白
原代码
.hero { position: relative; text-align: center; top: 6.7rem; width: 100%; } .hero > img { width: 100%; max-width: 1330px; height: 690px; object-fit: cover; }
<div class="hero"> <img src="https://static.nike.com/a/images/q_auto:eco/t_product_v1/f_auto/dpr_2.0/w_441,c_limit/9d1635ed-eed0-45b0-b34d-e00468e2f79e/tanjun-easyon-shoes-mplG1H.png" alt="Nike Tanjun EasyOn Shoes"> </div>
修改后的代码
.hero { position: relative; top: 6.7rem; width: 100%; overflow: hidden; /* 隐藏超出容器的图片部分 */ max-width: 1330px; /* 容器最大宽度匹配图片完整尺寸 */ margin: 0 auto; /* 容器居中,保留桌面端左右留白 */ } .hero > img { width: 100%; height: 690px; object-fit: cover; /* 保持图片比例,避免拉伸 */ object-position: left center; /* 图片左对齐,缩小时仅裁剪右侧 */ }
<div class="hero"> <img src="https://static.nike.com/a/images/q_auto:eco/t_product_v1/f_auto/dpr_2.0/w_441,c_limit/9d1635ed-eed0-45b0-b34d-e00468e2f79e/tanjun-easyon-shoes-mplG1H.png" alt="Nike Tanjun EasyOn Shoes"> </div>
关键修改说明
- 容器设置:给
.hero添加max-width:1330px和margin:0 auto,确保桌面端图片完整居中显示,保留原有左右留白;添加overflow:hidden,当屏幕宽度小于1330px时,自动隐藏超出容器的图片部分。 - 图片定位:设置
object-position:left center,让图片始终左对齐容器,屏幕缩小时只会裁剪图片右侧区域,左侧留白和主体位置保持不变。 - 高度与比例:固定
height:690px维持图片高度,object-fit:cover确保图片比例正常,不会因容器宽度变化而拉伸变形。
内容的提问来源于stack exchange,提问作者Thor The dog
相关产品推荐
相关产品推荐

