CSS布局求助:子元素宽度分配与图片溢出隐藏解决方案
解决方案
问题分析
原代码的核心问题:
- 父容器未设置
position: relative,导致.second-child的绝对定位基准不是父容器,left: 30%无法按预期生效 .second-child脱离flex流后,flex属性失效,且width: 100%让它超出了预期的50%宽度- 未设置层级关系,无法确保第一个子元素能遮挡第二个
修正后的代码
HTML(无需修改)
<section class="parent"> <div class="first-child"> <form> </form> </div> <div class="second-child"> <img src="你的图片地址" alt="示例图片"/> </div> </section>
CSS
.parent { width: 100%; height: 70vh; display: flex; margin: auto; position: relative; /* 关键:设置为绝对定位的基准容器 */ } .first-child { flex: 0 0 50%; /* 占父容器50%宽度 */ height: 100%; background-color: pink; border-top-right-radius: 100px; display: flex; justify-content: center; align-items: center; z-index: 1; /* 确保第一个子元素在上方,遮挡第二个 */ } .second-child { position: absolute; width: 50%; /* 占父容器50%宽度 */ height: 100%; left: 30%; /* 从父容器30%位置开始,左边20%区域被第一个子元素遮挡 */ overflow: hidden; /* 裁剪超出自身容器的内容(如果图片比例不合适) */ } .second-child img { display: block; width: 100%; height: 100%; object-fit: cover; /* 确保图片填满容器且不变形 */ }
原理说明
- 父容器添加
position: relative,让.second-child的绝对定位以父容器为参考 .first-child通过z-index:1提升层级,保证它能遮挡住.second-child的重叠部分.second-child设置width:50%和left:30%,刚好让它的左侧20%(父容器宽度的30%到50%区间)被.first-child覆盖,剩余30%(父容器50%到80%区间)正常显示object-fit: cover确保图片适配容器尺寸,避免溢出变形
内容的提问来源于stack exchange,提问作者Vũ Trần
相关产品推荐
相关产品推荐

