如何让.builder图片填充img-holder容器并从顶部溢出指定比例?
解决方案
修改后的CSS代码
.img-control{ display: flex; } .img-holder{ flex-basis: 50%; width: 228px; height: 255px; background-color: var(--primary-color); margin: 3.4rem 0rem 5rem 1rem; overflow: visible; /* 允许内容溢出容器 */ position: relative; } /* 移除冲突的伪元素,避免额外撑开容器高度 */ /* .img-holder:before{ content: ""; display: block; padding-top: 120%; } */ .builder{ position: absolute; top: -15%; /* 调整百分比控制顶部溢出幅度,比如-10%/-20% */ left: 0; width: 100%; height: 115%; /* 高度匹配溢出比例,确保填充容器同时溢出 */ object-fit: cover; /* 保持图片比例填充 */ z-index: 1; /* 确保图片在最上层 */ } .div{ flex-basis: 50%; &__bg{ &--mint{ width: 228px; height: 255px; background-color: var(--primary-color); margin: 3.4rem 1rem 5rem 0rem; } } &__copy{ padding: 3rem 1rem 0rem 1rem; color: #336B91; display: block; } }
关键调整说明
- 移除
.img-holder:before伪元素:原伪元素的padding-top:120%会基于容器宽度额外撑开高度,和你设置的固定height:255px冲突,导致图片定位异常。 - 调整
.builder参数:top: -15%:通过负数偏移让图片向上溢出容器,百分比可按需修改。height: 115%:高度设为容器高度加溢出比例,保证图片既填充容器,又有部分从顶部溢出。- 添加
z-index: 1:确保图片层级高于容器背景。
- 保留
overflow: visible:允许图片溢出容器,若需要裁切溢出部分,将其改为overflow: hidden即可。
内容的提问来源于stack exchange,提问作者huckleberry2021
相关产品推荐
相关产品推荐

