html,css:将表的调整高度调整为行数

时间:2017-05-30 20:17:44

标签: html css

<div class="modal-body">
              <div class="table-responsive">
                 <table id="table">
                   <thead>
                    <tr>
                       <th>...</th>
                           ...
                    </tr>
                   <thead>

                   <tbody>
                    <tr>
                       <td>...</td>
                           ...
                    </tr>
                   <thead>
                 </table> 
              </div>
        </div>

我想根据行数调整表格的高度。我想使用一些数字(N px)限制高度,但如果行数较少(填充小于N px),则表格应该更低。我试图设置max-height但没有成功(当时盒子是空的)。

编辑: 我试过了: fiddle

2 个答案:

答案 0 :(得分:1)

只需将高度添加到tr,这样表格就会加倍tr,我也会将id="table"更改为class="mytable",只是为了展示示例。

tr {
  height: 50px;
}

table *{
  border: 1px solid green;
  box-sizing: border-box;
}

.table-responsive{
  display: inline-block;
  max-height: 150px;
  overflow: auto;
}
<div class="modal-body">
  <div class="table-responsive">
    <table class="mytable">
      <thead>
        <tr>
          <th>tr here 111111</th>
          <th>tr here 222222</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>tr here 22222</th>
          <td>td here 22222</td>
        </tr>
        <tr>
          <th>tr here 33333</th>
          <td>td here 33333</td>
        </tr>
        <tr>
          <th>tr here 44444</th>
          <td>td here 44444</td>
        </tr>
            <tr>
          <th>tr here 55555</th>
          <td>td here 55555</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

<hr>

<div class="modal-body">
  <div class="table-responsive">
    <table class="mytable">
      <thead>
        <tr>
          <th>tr here 111111</th>
          <th>tr here 222222</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>tr here 22222</th>
          <td>td here 22222</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

答案 1 :(得分:0)

尝试使用以下代码,

&#13;
&#13;
table,td,th{
    border: 1px solid black;
    width:200px;
}

 thead,tbody{
    display:block;
 }
  
tbody{
  	max-height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
}
&#13;
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  
  <tbody>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr> <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr> <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;