[英]Why doesn't percentage height work with display: table-cell?
I'm trying to center both horizontally and vertically a div inside an outer div. 我试图在水平和垂直方向上将div放在外部div中。 It works when the outer div has specific width and height set in pixels like 它适用于外部div具有特定的宽度和高度设置像素
#countdownBox {
width: 700px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
but it fails when the height and width are percentages like 但是当高度和宽度都是百分比时,它会失败
#countdownBox {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
Why is this and is there a work around? 为什么会这样,是否有解决方法?
EDIT Here is the HTML with container CSS: 编辑这是带有容器CSS的HTML:
#countdownBoxContainer {
width: 100%;
height: 100%;
position: absolute;
bottom: 0;
left: 0;
z-index: 3;
}
<div id="countdownBoxContainer">
<div id="countdownBox">
<div>
hi there
</div>
</div>
</div>
Based on the fact that you have width and height of 100% declared I'm going to assume that you're not expecting anyone to have to scroll here. 基于您宣布宽度和高度为100%这一事实,我将假设您不希望任何人必须在这里滚动。 See this Fiddle where I have a working solution based on those parameters. 看到这个小提琴 ,我有一个基于这些参数的工作解决方案。
Remember that display: table-cell;
记住display: table-cell;
acts exactly like <td>
elements and they won't render correctly unless they're in a <table>
(or a container that is display: table;
). 与<td>
元素完全相同,除非它们位于<table>
(或者是display: table;
的容器)中,否则它们将无法正确呈现。
The other problem is that <html>
and <body>
aren't necessarily the height of the screen if the content is very small. 另一个问题是,如果内容非常小, <html>
和<body>
不一定是屏幕的高度。 html, body { height: 100%; }
html, body { height: 100%; }
fixes this but it's a bit hacky. html, body { height: 100%; }
修复这一点,但它是一个有点哈克。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.