Django模板中如何实现两个table表格并排显示
Django模板双表格并排展示解决方案
问题根因
你当前使用了Bootstrap的.table类,该类默认给表格设置了width: 100%属性,两个宽度为100%的元素无法在同一行展示,同时浮动布局未做清除浮动处理,也会引发父容器高度塌陷、元素错位等异常。
推荐解决方案
方案1:使用Bootstrap栅格系统(适配你已引入的Bootstrap框架,无需额外写冗余样式)
将父容器改为Bootstrap的row容器,两个表格分别放入等宽的栅格列中即可:
<div class="row"> <div class="col-6"> <table class="table table-striped table-bordered table-sm"> {% for item in product %} {% if item.orden_ref_id == orden.id %} <tr> <td> {{ item.articulo }} </td> </tr> {% endif %} {% endfor %} </table> </div> <div class="col-6"> <table class="table table-striped table-bordered table-sm"> {% for item in valor %} {% if item.refer_id == orden.id %} {% if item.show_ref == '2' %} <tr> <td> {{ item.costo }} </td> </tr> {% endif %} {% endif %} {% endfor %} </table> </div> </div>
如果需要调整两个表格的宽度比例,将col-6替换为col-4+col-8等其他栅格组合即可,同时默认支持响应式适配。
方案2:使用Flex布局(通用现代方案,兼容性好)
给父容器设置flex布局属性,两个表格按比例分配宽度:
<div style="display: flex; gap: 20px;"> <table style="flex: 1;" class="table table-striped table-bordered table-sm"> {% for item in product %} {% if item.orden_ref_id == orden.id %} <tr> <td> {{ item.articulo }} </td> </tr> {% endif %} {% endfor %} </table> <table style="flex: 1;" class="table table-striped table-bordered table-sm"> {% for item in valor %} {% if item.refer_id == orden.id %} {% if item.show_ref == '2' %} <tr> <td> {{ item.costo }} </td> </tr> {% endif %} {% endif %} {% endfor %} </table> </div>
flex:1表示两个表格平分父容器宽度,gap属性用于设置两个表格之间的间距,不需要可直接删除。
方案3:调整原有浮动方案(不推荐,需要额外处理样式规则)
给两个表格设置小于50%的宽度,同时给父容器添加清除浮动的属性:
<div style="overflow: hidden;"> <table style="float: left; width: 48%;" class="table table-striped table-bordered table-sm"> <!-- 原有表格逻辑保持不变 --> </table> <table style="float: right; width: 48%;" class="table table-striped table-bordered table-sm"> <!-- 原有表格逻辑保持不变 --> </table> </div>
内容的提问来源于stack exchange,提问作者Aidenweiss
相关产品推荐
相关产品推荐

