如何让flexbox行内的图片拉伸至容器最大宽度
解决图片适配蓝色容器的问题
要让图片填满右侧无空白、和蓝色容器高度一致且保持比例裁剪,你需要调整图片容器和图片的尺寸设置,具体修改如下:
关键修改点:
- 让图片所在的右侧section占满容器剩余宽度,同时强制其高度与左侧蓝色容器一致
- 给图片的父容器(figure)设置100%宽高,确保它能撑满所在的section
- 图片设置100%宽高,搭配
object-fit: cover实现按比例裁剪填满容器
修改后的CSS代码:
* { margin: 0px; padding: 0px; } .see-bike-rides-card { display: flex; height: 400px; /* 固定高度,确保左右两侧高度一致 */ width: 1000px; } .home-card-text { background: #80D0E5; padding: 1rem; } /* 调整右侧图片容器 */ .see-bike-rides-card > section:last-child { flex: 1; /* 占满容器剩余宽度 */ display: flex; } .see-bike-rides-card figure { width: 100%; height: 100%; overflow: hidden; /* 裁剪超出容器的图片部分 */ margin: 0; /* 清除figure默认外边距 */ } .see-bike-rides-card img { width: 100%; height: 100%; object-fit: cover; /* 按比例裁剪,填满容器 */ }
修改后的HTML代码:
<article class="see-bike-rides-card"> <section class="home-card-text"> <h2>Coolest Bike Rides in Brisbane</h2> <p>Check out our favourite spots to ride your bike in Brissy.</p> <div> <a href="#" class="button">See Bike Trails</a> </div> </section> <section> <figure> <img src="https://images.unsplash.com/photo-1515722265856-49cdff079949?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8" alt="Bike ride scene"> </figure> </section> </article>
修改完成后,右侧图片会完全填满容器,和左侧蓝色部分高度一致,同时保持图片比例、裁剪多余部分,不会出现右侧空白。
内容的提问来源于stack exchange,提问作者Blair A
相关产品推荐
相关产品推荐

