在Div元素内设置表格高度为100%

22

嗨,我想将表格高度设置为其父级div的100%,而无需在div中定义高度。我的代码不起作用。我不知道我错过了什么。 Fiddle链接link

<div style="overflow:hidden">
<div style="float:left">a<br />b</div>
<table cellpadding="0" cellspacing="0" height="100%" style="border:solid 1px #000000">
<tr>
<td valign="middle">c</td></tr>
</table>
</div>

4
它为什么不工作?在一个空的div上没有设置高度意味着它没有高度,因此将其设置为0的100%结果也是0... - Andy
Div的高度会根据其内容扩展,因此无论其高度如何,表格上的高度都应相同。 - user1903769
5个回答

40

请添加这行代码

body, html{height:100%}
div{height:100%}
table{background:green; width:450px}    ​

演示


1
NO. Body height 应该设置为 100%,以便为其内部的任何 div 指定 100% 的高度。 - Sowmya

1
这是如何做到的 -
HTML -
<div style="overflow:hidden; height:100%">
     <div style="float:left">a<br>b</div>
     <table cellpadding="0" cellspacing="0" style="height:100%;">     
          <tr><td>This is the content of a table that takes 100% height</td></tr>  
      </table>
 </div>

CSS-

html,body
{
    height:100%;
    background-color:grey;
}
table
{
    background-color:yellow;
}

查看演示

更新:好的,如果您不想将100%的高度应用于父容器,那么这里有一个jQuery解决方案,应该会对您有所帮助-

演示-使用jQuery

脚本-

 $(document).ready(function(){
    var b= $(window).height(); //gets the window's height, change the selector if you are looking for height relative to some other element
    $("#tab").css("height",b);
});

2
我们不能使用body和html高度100%,因为它会影响我的旧HTML。 - user1903769
如果不指定父元素的高度,就无法占用100%的高度。您应该查找jQuery或Javascript解决方案。 - Shiridish
我已经更新了答案,提供了一个jQuery的解决方案。看看它是否有帮助。 - Shiridish

1

你需要在div <div style="overflow:hidden">中设置高度,否则它不知道什么是100%


0

遇到了类似的问题。我的解决方案是给内部表格一个固定高度为1像素,并将内部表格中的td高度设置为100%。尽管一切都不顺利,但在IE,Chrome和FF中测试后,它运行良好!


-4

要将表格高度设置为其容器高度,我必须执行以下步骤:

1)设置“position: absolute”

2)删除单元格中多余的内容!


什么?position: absolute与此无关。您能解释一下为什么您认为它有关系吗? - katzenhut
我不是“想”。我做了我写的。 - Leon Rom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接