如何调整flex子项适配父容器,解决100vh两列布局图片溢出问题
修正方案
核心调整点
- 补全原代码中遗漏的CSS分号、修正HTML标签闭合错误
- 给flex容器子项
.wrapper添加flex: 1实现两列等分,同时添加min-height: 0解决flex布局子元素默认不收缩的兼容问题 - 存放图片的
.wrapper额外添加overflow: hidden和弹性布局属性,限制图片溢出的同时保证自适应逻辑生效 - 调整图片样式为最大宽高限制,避免图片拉伸变形
调整后完整代码
CSS
.section { width: 100vw; height: 100vh; background-color: blue; /* 避免页面默认边距导致出现滚动条 */ margin: 0; padding: 0; overflow: hidden; } .container { display: flex; width: 100%; height: 100%; align-items: center; gap: 20px; /* 可选,调整两列间距 */ padding: 20px; /* 可选,调整容器内边距 */ box-sizing: border-box; } .wrapper { flex: 1; min-height: 0; /* 关键属性,允许flex子项收缩内容 */ width: 100%; } /* 单独给图片父容器加样式 */ .wrapper:last-child { display: flex; justify-content: center; align-items: center; overflow: hidden; height: 100%; } img { max-width: 100%; max-height: 100%; object-fit: contain; }
HTML
<section class="section"> <div class="container"> <div class="wrapper"> <h1>Some heading</h1> <p>Lorem ipsum dolor sit amet</p> </div> <div class="wrapper"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png" alt="示例图片"> </div> </div> </section>
内容的提问来源于stack exchange,提问作者Taha
相关产品推荐
相关产品推荐

