如何强制 html 表格的高度?

问题描述 投票:0回答:1

不知道为什么,但这张桌子不听我的。我给它的高度/最大高度为 20px,它仍然显示所有行。

CSS:

table {
    border:1px solid black;
    overflow:hidden;
    height:20px;
    max-height:20px;
}

html:

<table>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
    <tr><td>this is a row</td></tr>
</table>

http://jsfiddle.net/foreyez/7demh/

html css
1个回答
6
投票

display:block;
添加到表格的 CSS 中:

table {
  border: 1px solid black;
  overflow: auto;
  height: 20px;
  max-height: 20px;
  display: block;
}
<table>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
</table>

这将使其填充可用的水平空间,因此如果您想限制它,请添加显式宽度:

table {
  border: 1px solid black;
  overflow: auto;
  height: 30px;
  max-height: 30px;
  display: block;
  width: 200px;
}
<table>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
  <tr>
    <td>this is a row</td>
  </tr>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.