【问题标题】:Formatting dynamically rendering table in HTML在 HTML 中格式化动态呈现表
【发布时间】:2019-07-29 16:41:35
【问题描述】:

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

只有其中一些条件会成立,这意味着每次呈现表格时每行的列数都会不同(且未知)。目前,这意味着行间距不均匀,导致某些行“突出”到表格的右侧。

有什么方法可以确保所有行的宽度相同(即,间隔使每行的每个单元格大小相等,并且每行最右边一列的末端对齐)?

【问题讨论】:

  • 所以,如果 condition 1、3、4、7、10、11 和 12 是 True,你会想要 element5elementelement12尽管&lt;td&gt; 元素的数量不匹配,但与&lt;table&gt; 的右边界垂直对齐?
  • 这是正确的 - 以及元素 1、7 和 11 垂直对齐到左侧。
  • ... 并在&lt;table&gt; 的整体宽度内平均分配&lt;td&gt; 宽度,而不管看起来是否与列对齐? 例如第一行的中间&lt;td&gt;(在我的示例中将包含 3 个项目)不会与第二行中的 2 个中的任何一个对齐或关联(视觉上)?
  • 这也是正确的 - 在谷歌搜索之后,我认为我可以使用 flexbox 获得类似的效果?

标签: html css html-table jinja2


【解决方案1】:

&lt;table&gt; 元素将尝试根据单元格数量最多的行建立列关系。

要完成您所追求的目标,我认为您需要覆盖表格 &lt;tr&gt; 的固有 display 属性 — 可能使用 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>

我应该注意到,因为 &lt;table&gt; 元素具有语义意义——这在某种程度上被用 Flexbox 覆盖表格结构而被混淆了——你最好使用 &lt;div&gt; 元素来完成这一点。

【讨论】:

    【解决方案2】:

    当每行的单元格数量不确定时,要使单元格大小相同,不幸的是,它们每个都需要在自己的表格中。诚然,这很混乱,但这只是 html 表格的性质,需要排列列。

    正如 Ito 所说,如果不显示真正的表格数据(以列主要形式),您最好使用其他元素。

    请注意,您还可以使用 colspan 来根据可能的列数的最小公倍数使用列总数来伪造事物。我之前已经完成了这项工作,但由于难以跨浏览器或通过不断发展的标准,它最终变得非常糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2015-11-02
      • 1970-01-01
      • 2010-10-31
      相关资源
      最近更新 更多