是否可以将div垂直居中于%height div?
答案 0 :(得分:15)
在这里以及整个互联网上都有足够的时间。快速搜索将为您带来大量的结果。无论如何,我首选的方法是使用display: table-cell;
和vertical-align: middle;
。有关示例,请参阅this page。 (请注意,这在IE6上不起作用。)
答案 1 :(得分:6)
如果你的内部div具有绝对高度(比如100px),你可以这样做:
.outerdiv{
position: relative; //or absolute, or fixed
height: 80%;
}
.innerdiv{
position: absolute;
width: 100px;
height: 100px;
top: 50%; // it's at 50% but not really centered
margin-top: -50px; // so just move it up by the half of its height :D
}
我不喜欢这个解决方案,我确信还有很多其他的可能性(可能使用表格或display: table-cell;
) - 但这是我想到的第一个... < / p>
答案 2 :(得分:3)
.outerdiv {
display: table-cell;
vertical-align: middle;
}
警告 - 不适用于所有浏览器!
答案 3 :(得分:0)
不需要px单位 更改顶部,底部,右侧,左侧或使用百分比 干杯
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
text-align: center;
white-space: nowrap;
overflow: hidden;">
<div style="position: relative;
display: inline-block;
height: 100%;
vertical-align: middle;"></div>
<div style="background-color: #FEEF88;
position: relative;
display: inline-block;
vertical-align: middle;">Hola todo el mundo :D</div>
</div>
</body>
</html>
答案 4 :(得分:0)
我更喜欢使用以下技术,它涉及两个容器:
display: table;
display: table-cell;
vertical-align: middle;
display: inline-block;
您可以将任何内容添加到内容框中,而无需考虑其宽度或高度!
此外,您可以通过将text-align: center;
添加到内部容器来轻松添加水平居中。
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
}
.centered-content {
display: inline-block;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Malcolm in the Middle
</div>
</div>
</div>
另见this Fiddle!