CSS - tr 上的固定高度和 table 上的固定高度?

CSS - fixed height on tr and fixed height on table?

我需要 table 具有固定高度的行,并且 table 本身必须具有固定高度。 例如,所有行的高度均为 8 像素,而 table 的高度为 400 像素。如果行数少于 table 的总高度,则 table 的剩余部分应该像一个间隙。

但是如果我在 table 上设置固定高度,css 会自动重新调整行高。

我需要 table 看起来像这样:

|row  |cont  |
|row  |cont  |
|row  |cont  |
|            |
|            |
|            |
|End of table|

我试过这个:

CSS:

.t-table {
  border: 1px solid black;
  height: 400px;
  border-collapse: collapse;
}
td {
  border: 1px solid black;
}

HTML:

<table class="t-table">
<tr style="line-height: 8px">
  <td>A</td>
  <td>B</td>
</tr>
<tr style="line-height: 8px">
  <td>1</td>
  <td>2</td>
</tr>
<tr>
  <td></td>
  <td></td>
</tr>
</table>

或者您可以在这里查看:https://jsfiddle.net/utrwqfux/

P.S. 因此,如果我在 table 上强制设置高度,它将忽略行上的高度。最后一个 tr 没有高度,所以想法是让它自动调整大小以填充空白。

    .t-table {
     border: 1px solid black;
     height: 400px;
     border-collapse: collapse;
     display: table-cell;
    }
    td {
     border: 1px solid black;
     padding:5px;
    }

https://jsfiddle.net/pf8g49h2/

基本上我是通过在 CSS 而不是 HTML 中创建 table 来做到这一点的。这给了更多的控制权。

HTML:

<div class="table">
    <div class="tr">
        <div class="td">A</div>
        <div class="td">B</div>
    </div>
    <div class="tr">
        <div class="td">1</div>
        <div class="td">2</div>
    </div>
</div>

CSS:

.table {
    background: rebeccapurple;
    display: table;
    height: 400px;
    table-layout: fixed;
    width: 400px;
}

.td {
    background: hotpink;
    display: table-cell;
    height: 8px;
    width: 200px;
}

实例:http://codepen.io/WartClaes/pen/mVxdQg?editors=1100

这里唯一的问题是 td 会比 8px 高,因为它们的内容比那个大。 8px是实际高度吗?

我同意 Wart Claes 将 div 显示为 table 元素与使用老式 table 布局的观点。但是您 运行 遇到的问题是浏览器正在向您的 table 添加一个 tbody 元素。此元素强制行高。要解决此问题,有两种方法。

1) 将tbody设置为显示为块,这将使浏览器忽略其显示属性并完全按照您的意愿显示。

https://jsfiddle.net/benneb10/utrwqfux/1/

tbody{
  display:block;
}

2) 用tbody设置table的table高度:

tbody{
  height:400px;
  overflow:auto;
  overflow-x:hidden;
  border: 1px solid black;
}

但是,这样做不会让您的 table 达到您想要的 400 像素。它会强制 tr 正好是 8px。

https://jsfiddle.net/benneb10/utrwqfux/2/

您可以将height:8px设置为第一个和第二个tr。并从最后 tr.

中的空单元格中删除中间边框

.t-table {
  border: 1px solid black;
  height: 400px;
  border-collapse: collapse;
}
.t-table td {
  border: 1px solid black;
}
.t-table td:empty {
  border-left: 0;
  border-right: 0;
}
<table class="t-table">
  <tr style="line-height: 8px; height: 8px;">
    <td>A</td>
    <td>B</td>
  </tr>
  <tr style="line-height: 8px; height: 8px;">
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td></td>
    <td></td>
  </tr>
</table>

这将是通过保持垂直线将 table 延伸到一定高度的正确解决方案。

CSS

table {
  border: 1px solid black;
  min-height: 400px; /* table height here */
  border-collapse: collapse;
}
td {
  border: 1px solid black;
}
tr {
    height: max-content;
}
tr:last-child {
    height: auto;
}

实例:https://jsfiddle.net/sandy912/20z45kaj/3/