[英]Center a 'div' vertically in a % height 'div'
是否可以将div垂直居中 % 高度div ?
这已经在这里以及整个互联网上被问到了足够多的时间。
快速搜索将为您带来大量结果。 无论如何,我的首选方法是使用display: table-cell;
和vertical-align: middle;
. 有关示例,请参阅此页面。 (请注意,这不适用于Internet Explorer 6 。)
如果您的内部div具有绝对高度(假设为 100 像素),您可以这样做:
.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;
) - 但这是我想到的第一个......
.outerdiv {
display: table-cell;
vertical-align: middle;
}
警告 - 它不适用于所有浏览器!
不需要 px 单位。
更改top
、 bottom
、 right
、 left
或使用百分比:
<!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>
我更喜欢使用以下技术,它涉及两个容器:
display: table;
display: table-cell;
vertical-align: middle;
display: inline-block;
您可以将任何您想要的内容添加到内容框中,而无需关心其宽度或高度!
此外,您可以通过添加text-align: center;
轻松添加水平居中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>
另见这个小提琴!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.