And*_*rea 43 html css css-tables
我正在尝试设计一个有一些表格的页面.似乎样式表比应该是更痛苦.
问题如下.桌子应该有一个固定的高度,并且当底部太少时,显示底部的空白区域 - 或者当内容太少时显示空白 - 或者显示垂直滚动条.除此之外,表格有一个不应滚动的标题.
据我所知,thead不滚动是表的默认行为.拉伸tfoot可以很好地填充白色空间.可悲的是,似乎我可以放在桌子高度上的每一个约束都被高兴地忽略了.我试过了
table {
    height: 600px;
    overflow: scroll;
}
Run Code Online (Sandbox Code Playgroud)
我试过了max-height.我试图绝对定位表并给出顶部和底部坐标.我试图在Firebug中手动编辑高度,看看它是否与CSS特异性有关.我也尝试过设置高度tbody.事实上,无论我的努力如何,表格的内容始终保持高水平.
当然我可以伪造一个带有div结构的表,但它实际上是一个表,我担心使用div我可能遇到一些问题,其中一些列可能没有正确对齐.
我怎么能给桌子一个高度?
Dan*_*scu 25
注意 此答案现在不正确.我可能会在以后再回来.
正如其他人所指出的那样,除非将其显示设置为,否则无法设置表的高度block,但随后会得到一个滚动标题.所以你要寻找的是设置height和display:block在tbody孤独:
<table style="border: 1px solid red">
    <thead>
        <tr>
            <td>Header stays put, no scrolling</td>
        </tr>
    </thead>
    <tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
        <tr>
            <td>cell 1/1</td>
            <td>cell 1/2</td>
        </tr>
        <tr>
            <td>cell 2/1</td>
            <td>cell 2/2</td>
        </tr>
        <tr>
            <td>cell 3/1</td>
            <td>cell 3/2</td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
这是小提琴.
display: block;为tableposition: sticky; top: 0;为标题行设置<table style="display: block; height: 100px; overflow: auto;">
  <thead>
    <tr>
      <td style="position: sticky; top: 0;">Header stays put</td>
      <td style="position: sticky; top: 0;">Layout aligned</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>foo1</td>
      <td>Header stays put</td>
    </tr>
    <tr>
      <td>foo2</td>
      <td>Header stays put</td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/0zxk18fp/
在 Chrome、Firefox、Safari、Edge 上测试
您可以使用以下 css 来完成此操作。
.scroll-thead{
    width: 100%;
    display: inline-table;
}
.scroll-tbody-y
{
    display: block;
    overflow-y: scroll;
}
.table-body{
    height: /*fix height here*/;
}
Run Code Online (Sandbox Code Playgroud)
以下是 HTML。
<table>
 <thead class="scroll-thead">
          <tr> 
           <th>Key</th>
           <th>Value</th>
          </tr> 
         </thead>
         <tbody class="scroll-tbody-y table-body">
          <tr> 
          <td>Blah</td> 
          <td>Blah</td> 
          </tr> 
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
        在大多数情况下,可以使用一个简单的解决方法,将表包装在 a 中div,然后max-height为其提供 a div:
.scrollable-wrapper {
  max-height: 400px;
  overflow: auto;
}
/* Add also the following code if sticky header is wanted */
.scrollable-wrapper table thead th {
  background: #afa;
  position: sticky;
  top: 0;
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
}
Run Code Online (Sandbox Code Playgroud)
<div class="scrollable-wrapper">
  <table>
    <thead>
      <tr>
        <th>Id</th>
        <th>Text</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)
代码笔: https: //codepen.io/Conejoo/pen/NWpjmYw