(1)父元素设置display:table;子元素设置display:table-cell;vertical-align:middle;缺点:ie8以下不支持。
<!doctype html>
<html>
<head>
<style>
#wrapper {
display: table;
height:200px;
}
#cell {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="cell">Content goes here</div>
</div>
</body>
</html>
(2)元素的宽高一定,设置为绝对定位,top:50%;margin-top等于负的元素高度的一半.
<!doctype html>
<html>
<head>
<style>
#wrapper{
position:absolute;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
width:200px;
height:200px;
background:maroon;
}
</style>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
(3)元素的宽高一定,设置为绝对定位,top:0;bottom:0;margin:auto;
<!doctype html>
<html>
<head>
<style>
#wrapper{
position:absolute;
top:0;
bottom:0;
margin:auto;
width:200px;
height:200px;
background:maroon;
}
</style>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
(4)只能将等行文本垂直居中,设置height和line-height相等就好。
(5)flex布局实现垂直居中
<!doctype html>
<html>
<head>
<style>
#wrapper{
display: flex;
justify-content:center;
align-items:center;
background:maroon;
width:100px;
height:100px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="content">center</div>
</div>
</body>
</html>
(6)给content前面加一个同级元素,并且设置height:50%;margin-bottom等于负的contentHeight的一半,float:left;content清除浮动,content就可以垂直居中显示。
<!doctype html>
<html>
<head>
<style>
#wrapper{
width:400px;
height:400px;
border:1px solid #000;
}
.floater {
float:left;
height:50%;
margin-bottom:-120px;
}
#content {
clear:both;
height:240px;
position:relative;
background:maroon;
}
</style>
</head>
<body>
<div id="wrapper">
<div class="floater"></div>
<div id="content"></div>
</div>
</body>
</html>