html - 在 HTML 中格式化动态呈现表

标签 html css html-table jinja2

我有一个 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/

相关文章:

css - 两个动态 div 之间的空间

html - 在导航栏上插入 Logo ,无需 Bootstrap

javascript - 将 CSS 链接到 Nodejs 服务器的 HTML

css - Div 页面设计在其他分辨率下看起来不对

javascript - 在窗口可调表上寻找固定标题

javascript - 如何在打印布局 html 中设置 img 样式

css - 当我尝试使用`transform : rotateY(60deg);` it will not flip 60deg 翻转图像时

html - 如何使 div/video 始终为浏览器窗口的大小,并固定在特定位置

javascript - 在 HTML 和 Javascript 中对表格进行排序 - 第一列的问题

css - 神秘的底边