如何实现文本约束容器内、图片溢出容器右侧的响应式布局?
响应式布局解决方案
需求回顾
要实现的布局效果:
- 文本始终约束在居中的固定宽度容器内,与其他区块保持响应式对齐
- 图片溢出容器,始终贴靠页面右侧,无padding、margin
- 解决当前方案中图片高度不匹配的问题
简洁实现方案
核心思路
- 文本容器保留在居中固定宽度容器内,确保对齐一致性
- 图片容器脱离文本容器的宽度限制,直接绑定到页面右侧视口
- 通过
object-fit保证图片比例正常,同时让容器高度自适应内容(文本或图片的最大高度)
修改后的代码
CSS 代码
/* 控制背景与整体布局的基础容器 */ .text-2 { position: relative; overflow: hidden; /* 可选:避免极端场景下图片溢出页面 */ } .container2 { width: 100%; } .inner { max-width: 1320px; /* 改为max-width,小屏幕自动收缩 */ margin: 0 auto; padding: 0 20px; /* 小屏幕添加内边距,防止文本贴边 */ } .hero { display: flex; align-items: stretch; /* 强制子元素高度一致 */ min-height: 400px; /* 可选:设置最小高度,避免内容过少时布局坍塌 */ } .hero-text { flex: 0 0 50%; /* 固定占inner容器的50%宽度 */ display: flex; flex-direction: column; justify-content: center; /* 文本垂直居中 */ padding-right: 20px; /* 文本与图片之间预留间隙 */ } .hero-image { position: absolute; top: 0; right: 0; width: 50vw; /* 占视口右侧50%宽度 */ height: 100%; /* 与父容器高度同步 */ } .hero-image img { width: 100%; height: 100%; object-fit: cover; /* 保证图片比例,填满容器,避免拉伸变形 */ border-bottom-left-radius: 200px; } /* 移动端响应式适配 */ @media (max-width: 768px) { .hero { flex-direction: column; } .hero-text { width: 100%; padding-right: 0; padding-bottom: 20px; } .hero-image { position: static; width: 100%; height: auto; } .hero-image img { border-radius: 60px; } }
HTML 代码
<section class="text-2 <?php echo $background_colour ?? ''; ?>"> <div class="container2"> <div class="inner"> <div class="hero"> <div class="hero-text"> <div class="heading"> <h2 class="section-heading">Title</h2> </div> <div class="paragraph"> <p>Cairn is making significant investment, forward funding €30 million, in order to ensure Seven Mills’ holistic development. This will be added to €186 million invested by the Urban Regeneration Development Fund and €18.8 million by the National Transport Authority.</p> </div> </div> </div> </div> <div class="hero-image"> <img src='https://www.cbre.ie/resources/fileassets/IE-AdminUI-160/e402a1af/Dundrum-Shopping-Centre-inside_Photo_3_large.jpg' /> </div> </div> </section>
关键改进点
- 将图片容器从固定宽度的
.inner中移出,直接绑定到.container2,确保能不受限制溢出到页面右侧 - 使用
object-fit: cover处理图片缩放,解决原方案中图片高度变形、截断的问题 - 通过
align-items: stretch让文本容器与图片容器高度完全同步 - 给
.inner添加小屏幕内边距,优化移动端文本显示效果 - 移动端自动转为垂直布局,图片占满宽度,提升移动端体验
内容的提问来源于stack exchange,提问作者Toby
相关产品推荐
相关产品推荐

