Bootstrap div并排对齐及多余空间自动填充的桌面端布局问题
解决思路
你当前的问题本质是使用了Bootstrap的flex栅格布局将页面划分为左右两个固定宽度的半栏,左栏的文本内容被限制在半宽容器内,自然无法填充图片下方的全宽空间。要实现文字环绕图片的效果,可改用浮动布局实现,修改方案如下:
1. 调整HTML结构
删除原有拆分左右栏的.row及两个.col-md-6容器,将图片容器放到段落内容的最前方,合并两段段落的容器,修改后代码如下:
<div class="col-11"> <div style="margin-left:10px;margin-right:10px;"> {% for news in news %} <h1 class="text-center" style="color: black; margin-top:20px; font-size:50px;">{{news.title}}</h1> <!-- 替换原有.row部分的代码 --> <div class="content-wrap" style="color: #025; margin-top:20px; font-size:20px;"> {% if news.image %} <div class="img-wrapper"> <img src="{{news.image.url}}" alt="" class="img"> </div> {% endif %} {% if news.para_one %} <p>{{news.para_one|safe}}</p> {% endif %} {% if news.para_two %} <p>{{news.para_two|safe}}</p> {% endif %} </div> <!-- 原有后续结构保持不变 --> <div class="col-12"> {% if news.disclaimer %} <p style="border:1px solid #025; border-top: 5px solid #025; font-size:20px; font-weight:700">Disclaimer :<span style="font-weight: 500;">{{news.disclaimer}}</span></p> {% endif %} </div> <div style="margin-bottom: 20px;"> <p style="margin-left:10px; font-size :25px; font-weight:700;">Written By : <span style="color: #025;">{{news.written_by}}</span> </p> <p style="margin-left:10px; font-size :25px; font-weight:700;">Date & Time: <span style="color: #025;">{{news.joined_date}}</span> </p> </div> {% endfor %} </div>
2. 替换原有CSS代码
删除原有row > .col-md-6:last-child:nth-child(odd)相关规则,更新为以下浮动相关样式:
.col-11{ margin-left: auto; margin-right: auto; height: 100%; background-color: #fff; } /* 桌面端样式 */ @media screen and (min-width: 601px) { .img-wrapper { float: right; margin: 0 0 16px 16px; } .img { height: 400px; width: 650px; object-fit: cover; /* 可选,避免图片拉伸变形 */ } /* 清除浮动,避免后续内容排版错位 */ .content-wrap::after { content: ""; display: table; clear: both; } } /* 移动端样式 */ @media screen and (max-width: 600px) { .img{ height: 200px !important; width: 100% !important; margin-bottom: 16px; } }
方案说明
浮动是CSS原生支持的文字环绕排版方案,完全匹配需求:
- 桌面端图片固定在右侧,高度400px,段落内容较短时和图片左右并排显示
- 段落内容超过400px时,自动填充图片下方的全宽区域
- 移动端自动取消浮动,图片占满整行宽度,段落排在图片下方,和原有移动端表现一致
- 兼容图片为空的场景,无图片时段落自动占满全宽
内容的提问来源于stack exchange,提问作者Shreyash mishra
相关产品推荐
相关产品推荐

