div 高度:100%; 在使用 display:table-cell 时无法正常工作

14

我的代码在之前是正常工作的

<!DOCTYPE html>
<html>
<body style="position:fixed; top:0px; left:0px;bottom:0px; right:0px;  margin:0px;">
<div style="height:100%; width:100%; border:solid;"></div>
</body>
</html>

但是当我添加display:table-cell;到

中使用vertical-align时,它就不起作用了。

<!DOCTYPE html>
<html>
<body style="position:fixed; top:0px; left:0px;bottom:0px; right:0px;  margin:0px;">
<div style="height:100%; width:100%; border:solid; display:table-cell;vertical-align:middle;"></div>
</body>
</html>

我希望div能覆盖body中的全部空白区域。


2
https://dev59.com/YXA75IYBdhLWcg3wFE6b - Massimiliano Peluso
好的,你目前在屏幕上观察到什么? - Ashwin Krishnamurthy
请尝试这些代码,因为解释会浪费我们双方很多时间,而且也不能保证您理解我想要表达的理论。 - user1432124
为什么在DIV已经是块级元素的情况下,你还想将其设置为display table-cell或row? - Dipak
因为我想使用vertical-align属性。 - user1432124
3个回答

18

你的代码应该可以正常工作了。

<html>
<body style="position:fixed; top:0px; left:0px;bottom:0px; right:0px;  margin:0px;">
    <div style='display : table; width : 100%; height : 100%'>
    <div style='display : table-row;'>
        <div style="border:solid; display : table-cell;">
        </div>
    </div>
    </div>
</body>
</html>

经验法则:在涉及display : table-cell时,始终要有适当的标记。


示例


1
@Ashwin,当你可以简单地使用<table><tr><td>时,为什么要使用display: table;display: table-cell; - Pacerier
2
@Pacerier 因为更广泛的网页设计社区已经决定 table 只用于显示表格数据。尽管事实上 表格布局在所有浏览器中都能正常工作,无论新旧,而且不需要使用 CSS hack 和诡计。毕竟,表格被认为是有害的。 - Yuck
2
@Yuck,所以表格被认为是有害的,只是为了被认为是有害吗?这让我想起了我在https://dev59.com/rX_aa4cB1Zd3GeqP11jo收到的那种回答。 - Pacerier
1
@Pacerier 我是在提到“goto语句被认为是有害的”。另请参见 - http://en.wikipedia.org/wiki/Considered_harmful - Yuck
5
display: table应用在非table元素上并非比将display: inline应用在非span元素上更“hack”。当文档的逻辑结构与呈现需求不同时,使用非默认的display属性是有意义的。这与“表格布局”是否“有害”无关,因为在两种情况下,布局渲染都是基于完全相同的输入:表格显示。 - nmclean
显示剩余2条评论

1

你需要将所有父元素的高度设置为100%,然后...

html, body {
    height: 100%
}

试一下,这对我有用。最好在此之前删除您设置给body元素的所有CSS属性。


1
它根本不起作用。顺便说一句,删除这个回答并恢复你失去的声誉。 - user1432124
@somebodyisintrouble 这个解决方案效果不错。他只是需要清楚地解释一下。请检查我的答案。 - Dipak

1

如果容器的高度与 div.table > div.table-row > table.table-cell 相同,这可能有点棘手。其中最简单的方法之一是添加

.table {
    position: absolute;
}

在这种情况下,如果您添加


.table {
    height: 100%;
}

那将适应其父元素的高度。


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