1.方法一
.parent {
width:800px;
height:500px;
border:2px solid #000;
position:relative;
}
.child {
width:300px;
height:200px;
margin:auto;
position:absolute;/*设定水平和垂直偏移父元素的50%,
再根据实际长度将子元素上左挪回一半大小*/
left:50%;
top:50%;
margin-left: -150px;
margin-top:-100px;
background-color: red;
}
2.方法二
.parent {
width:800px;
height:500px;
border:2px solid #000;
position:relative;
}
.child {
width:200px;
height:200px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background-color: red;
}
3.方法三
将元素嵌套在一个table中
要实现垂直居中,container 的display:table;而wrapper的display:table-cell;同时vertical-align:middle;就可以实现div里的图片水平垂直居中。
这样则要应用三层div 1.container:table 2.wapper:table-cell 3.div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>div水平垂直居中</title>
<style type="text/css">
*{
margin:0;
padding:0;
}
div.container{
background-color:pink;
border:2px solid #000;
width:500px;
height:500px;
margin:0 auto;
display:table;
margin-top:20px;
}
div.wrapper{
text-align:center;
display:table-cell;
vertical-align:middle;
}
div.wrapper img{
border:1px solid #ddd;
}
</style>
<!--[if lte IE 7]>
<style type="text/css">
div.container{
position:relative;
}
div.wrapper{
position:absolute;
left:50%;top:50%;
}
div.wrapper img{
position:relative;
left:-50%;top:-50%;
}
</style>
<![endif]-->
4.方法四:
.parent {
width:800px;
height:500px;
border:2px solid #000;
display:table-cell;
vertical-align:middle;
text-align: center;
}
.child {
width:200px;
height:200px;
display:inline-block;
background-color: red;
}