【发布时间】:2012-07-31 21:54:22
【问题描述】:
我有一个固定大小的容器,其中包含未知数量的自定大小段落和可能的其他元素。在该内容之后我也有一张桌子。我想让表格填满容器的剩余高度。
我有以下 HTML:
<div id="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mattis. Sed semper dui sed ante. Sed luctus tincidunt nisl. Proin iaculis adipiscing nisl. Class aptent taciti sociosqu ad litora amet.</p>
<p>Lorem ipsum dolor sit amet, consectetur cras amet.</p>
<table>
<thead>
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
<th>Four</th>
</tr>
</thead>
<tbody>
<tr>
<td>111</td>
<td>222</td>
<td>33333</td>
<td>4444</td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td>33333</td>
<td>4444</td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td>33333</td>
<td>4444</td>
</tr>
<tr>
<td>111</td>
<td>222</td>
<td>33333</td>
<td>4444</td>
</tr>
</tbody>
</table>
</div>
使用以下 CSS:
#container {
width: 500px;
height: 500px;
background: red;
}
p {
margin-bottom: 20px;
}
table {
height: 100%;
width: 100%;
}
table,
table th,
table td{
border: 1px solid black;
}
这样做会导致表格占用容器的高度,而不仅仅是剩余区域。我尝试在 CSS 中将容器和子项设置为表格和表格行,这会导致其他元素太大或在其边距内松动。
可以在以下位置找到小提琴:http://jsfiddle.net/QLwkU/
我希望有一个纯 CSS 解决方案,但如果它是一个合理且可重用的 jQuery 解决方案,我没有问题。
我试过了:
var totalHeight = 0;
$('#container').children(':not(table)').each(function(){
totalHeight += $(this).outerHeight(true);
});
$('#container table').css({'height': ($('#container').outerHeight() - totalHeight)});
但这使得在需要时向表格添加边距变得更加困难。
任何想法或建议将不胜感激。
【问题讨论】:
-
为什么不设置 height:auto;或高度:100%;到容器?
-
因为我有一个固定的容器高度,我不希望容器自行调整大小。我只希望表格在放置其他内容后仅占用剩余空间。
-
您需要如何跨浏览器?您可以使用
display: table-cell或flexible box model,但浏览器支持有限(对于 flexbox 非常有限)。你确定你想让你的表格的单元格根据兄弟尺寸改变高度吗? -
它至少需要在 IE-8 中工作。
标签: html css html-table