<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS 网页布局 - 菜鸟教程(runoob.com)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#login_frame {
width: 400px;
height: 260px;
padding: 13px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -200px;
background-color: rgba(240, 255, 255, 0.5);
border-radius: 10px;
text-align: center;
}
#wrapper
{display:table;width:300px;height:300px;background:#000;margin:0 auto;color:red;
}
#cell
{display:table-cell; vertical-align:middle;
}
</style>
</head>
<body>
<div id="login_frame">
<div id="wrapper">
<div id="cell">
<p>测试垂直居中效果测试垂直居中效果</p>
<p>测试垂直居中效果测试垂直居中效果</p>
</div>
</div>
</div>
</body>
</html>
总结:
(1)单纯用模拟表格法效果不行,只能将容器内元素剧中
将容器设置为display:table,然后将子元素也就是要垂直居中显示的元素设置为display:table-cell,然后加上vertical-align:middle来实现。
(2)配合div居中方法,让一个div块在整个屏幕居中:
width: 400px;
height: 260px;
padding: 13px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -200px
(其中的margin-left:和margin-top最好是设为width和height的一半值,那样是完全居中的效果,当然记得前面要加个负号!)
参考地址: