You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap设置margin后Div换行异常问题求解

解决Bootstrap每行3个卡片被外边距挤换行的问题

问题根源很明确:Bootstrap栅格基于12列布局,col-md-4刚好占1/3宽度(4×3=12),但m-1给卡片添加了左右外边距,导致每个卡片的总宽度(列宽+左右margin)超过4份,三个卡片加起来总宽度超出12列阈值,第三个自然被挤到下一行。

以下是几种可行的解决方案:

方案一:用Bootstrap行间距类替代卡片外边距(推荐)

这是最贴合Bootstrap规范的做法,去掉卡片的m-1,给外层row添加g-*系列间距类(比如g-2,数值可按需调整),Bootstrap会自动在列之间生成合适的间距,完全不会破坏栅格布局:

修改主模板的row定义:

{% for plant in plants %}
    {% if forloop.counter0|divisibleby:3 %}
        <div class="row row-cols-3 g-2">
    {% endif %}
    {% include 'included/_plant_cell.html' %}
    {% if forloop.counter|divisibleby:3 %}
        </div>
    {% endif %}
{% endfor %}

修改_plant_cell.html,移除m-1:

<div class="plant-cell card col-md-4">
   <div class="card-body">
      <div class="card-text">
        {{ plant.name }}
      </div>
   </div>
</div>

方案二:修复未闭合的row标签(额外优化)

如果植物总数不是3的倍数,原模板会留下未闭合的row标签,导致HTML结构错误。可以调整判断逻辑,在循环结束时强制闭合最后一个row:

{% for plant in plants %}
    {% if forloop.counter0|divisibleby:3 %}
        <div class="row row-cols-3 g-2">
    {% endif %}
    {% include 'included/_plant_cell.html' %}
    {% if forloop.counter|divisibleby:3 or forloop.last %}
        </div>
    {% endif %}
{% endfor %}

方案三:改用内边距替代外边距(保留卡片间距感)

如果一定要给卡片添加间距,可把m-1换成p-1(内边距),这样不会增加卡片总宽度,只是扩大卡片内部的空白区域:

<div class="plant-cell card col-md-4 p-1">
   <div class="card-body">
      <div class="card-text">
        {{ plant.name }}
      </div>
   </div>
</div>

内容的提问来源于stack exchange,提问作者Dimon Agon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 14:25:05