我有一个 HTML 表格,其中的行由 jinja2 标签填充:
<table cellpadding="10">
<tr>
<td colspan="4">{{element1}}</td>
</tr>
<tr class="playerrow">
{% if condition1 = True %} <td>{{element2}}</td> {% endif %}
{% if condition2 = True %} <td>{{element3}}</td> {% endif %}
{% if condition3 = True %} <td>{{element4}}</td> {% endif %}
{% if condition4 = True %} <td>{{element5}}</td> {% endif %}
{% if condition5 = True %} <td>{{element6}}</td> {% endif %}
</tr>
<tr class="playerrow">
{% if condition6 = True %} <td>{{element6}}</td> {% endif %}
{% if condition7 = True %} <td>{{element7}}</td> {% endif %}
{% if condition8 = True %} <td>{{element8}}</td> {% endif %}
{% if condition9 = True %} <td>{{element9}}</td> {% endif %}
{% if condition10 = True %} <td>{{element}}</td> {% endif %}
</tr>
<tr class="playerrow">
{% if condition11 = True %} <td>{{element11}}</td> {% endif %}
{% if condition12 = True %} <td>{{element12}}</td> {% endif %}
{% if condition13 = True %} <td>{{element13}}</td> {% endif %}
</tr>
</table>
只有其中一些条件会成立,这意味着每次呈现表格时每行的列数将不同(且未知)。目前,这意味着行间距不均匀,导致某些行“伸出”表格的右侧。
有什么方法可以确保所有行的宽度相同(即,每行的每个单元格大小相等,并且每行最右边一列的末尾对齐)?
最佳答案
<table>
元素将尝试根据单元格数最多的行建立柱状关系。
为了完成您所追求的目标,我认为您需要覆盖固有的 display
你表的属性 <tr>
— 可能与 Flexbox 一起使用。
table {
border: 2px solid #ddd;
}
tr {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
}
tr td {
border: 1px solid #bbb;
flex: 1 1 auto;
}
<table cellpadding="10">
<tr>
<td colspan="4">element 1</td>
</tr>
<tr class="playerrow">
<td>element 2</td>
<td>element 4</td>
<td>element 5</td>
</tr>
<tr class="playerrow">
<td>element 7</td>
<td>element 10</td>
</tr>
<tr class="playerrow">
<td>element 11</td>
<td>element 12</td>
</tr>
</table>
我应该注意到,因为 <table>
元素具有语义意义——通过使用 Flexbox 覆盖表格结构有点混淆——使用 <div>
可能会更好地为您服务实现这一目标的要素。
关于html - 在 HTML 中格式化动态呈现表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55049821/