图片Hover缩放异常求助:保留边框时首张图片失效
解决图片Hover缩放时第一张异常的问题
问题根源在于行内元素的布局冲突:.examples用text-align: center居中图片,同时给img设置了margin: auto,但img默认是行内替换元素,margin: auto对行内元素不生效,加上边框的存在,导致第一张图片的布局计算出现偏差,hover缩放时表现异常。
解决方案1:改用Flex布局(推荐)
用Flex布局统一控制图片的居中与间距,让两张图片的布局规则完全一致,既能保留边框,又能让hover缩放正常工作:
.examples { display: flex; justify-content: center; gap: 10px; /* 图片间的间距,可按需调整 */ margin-top: 20px; } .examples img { aspect-ratio: 3/2; object-fit: contain; padding: 10px; width: 20%; background-color: rgba(10, 10, 10, .65); border: 2px solid rgba(255, 255, 255, .09); backdrop-filter: blur(4px); border-radius: 7px; transition: transform .4s; } .examples img:hover { transform: scale(2.5); }
HTML代码无需修改:
<div class="examples"> <img src="https://source.unsplash.com/user/c_v_r/400x400" alt="Free unsplash image"> <img src="https://source.unsplash.com/user/c_v_r/400x400" alt="Free unsplash image"> </div>
解决方案2:将图片设为行内块元素
如果不想改动容器布局,给img添加display: inline-block并去掉无效的margin: auto,同样能解决问题:
.examples img { /* 其他原有样式不变 */ display: inline-block; margin: 0 5px; /* 可选,添加图片间距 */ }
内容的提问来源于stack exchange,提问作者Kris
相关产品推荐
相关产品推荐

