HTML table: 如何让所有行的高度相等?

HTML table: how to make all rows equal height?

我正在 HTML 中生成一个 table。我有很多行,其计数保存在变量 {{ items|length }}

如何使除 header 行以外的所有行的高度相同?

我试过:

<style>
     table.equalDivide th { width:100 / {{ items|length }} %; }
</style>

但这行不通。

所有行都应具有最高行的高度(下图中的 12:00 - 14:00)。

编辑: 我想你想要发生的事情已经正常发生了。我创建了一个 JSFiddle 来显示大单元格将如何强制同一行中的其他单元格具有其高度。我很好奇你是否发生了其他事情。对不起,如果我误会了你。


只需为所有 tr 应用高度。如果您希望高度取决于行数,只需相应地更改 css 规则即可。

HTML:

<table>
<tbody>
<th>Title</th>
<tr><td>Foo</td></tr>
<tr><td>Bar</td></tr>
<tr><td>Baz</td></tr>
</tbody>
</table>

CSS:

tr {
  height: 50px;
}

我不知道 CSS 无法做到这一点。

你所能做的(我认为)是在你的 onload() 函数中通过遍历 table 行获得最大的行高(table.rows[..].offsetHeight(我希望那是 right-if 不是,尝试最大的单元格高度),然后将 table 中每一行的高度设置为该值。

这是我能做到的最简单的方法 - 但它有效...

使用记事本或类似工具(推荐使用 Notepad++)编辑您的 HTML 文件,如下所示: (注意:语法至关重要 - 严格遵守 - 特别是单引号或双引号)

1:给你的 table 一个唯一的 ID:table id="myTable" ...

2:给你的body元素一个onload函数:body onload="resizeTable('myTable');" ...

3:在你的头部添加:

<script type="text/javascript">
function resizeTable(tableID)
{
var tbl=document.getElementById(tableID), biggestRow=0, rowHeight=0, row=0;
for (row=0; row < tbl.rows.length; row++) {     //find biggest row height
    rowHeight=parseInt(tbl.rows[row].offsetHeight);
    if (rowHeight > biggestRow) {biggestRow=rowHeight;}
}
for (row=0; row < tbl.rows.length; row++) {     //set all rows to biggest row height
    tbl.rows[row].style.height=biggestRow + "px";
}
}
</script>

很简单,使用JQuery:

//variable to store the highest cell height
var highestHeight = 0;

//Loop through all the table cells to get the highest height
$('td').each(function(index, element) {
  highestHeight = Math.max(highestHeight, $(element).outerHeight());
});

//Set the height of all table cells to the highest height
$('td').height(highestHeight);
table {
  width: 100%;
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>single line text</td>
      <td>double line<br />text</td>
    </tr>
    <tr>
      <td>2nd single line text</td>
      <td>2nd brother of single line</td>
    </tr>
    <tr>
      <td>triple<br/>line<br/>text here</td>
      <td>triple<br/>line's<br/>brother</td>
    </tr>
  </tbody>
</table>

据我所知,你不能将 CSS Grid 或 Flexbox 与 <table> 一起使用,如果你只想使用 CSS,你可能不得不不使用<table> 并使用 <div> 和适当的 CSS 类.

开始学习 Flexbox 的一个好地方是 Flexbox Froggy and CSS Grid Garden for CSS Grid