1.溢出法
介绍:外层div相对定位,内层div绝对定位
子容器绝对定位,top:0,bottom:0,left:0,right:0,margin:auto
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css">
html,body{
margin: 0; padding: 0;
}
.divParent {
position:relative;
width:600px;
height:400px;
background:#ddd;
margin: 0 auto;
}
.divChild {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
background:green;
width:30%;
height:30%;
}
</style>
</head>
<body>
<div class="divParent">
<div class="divChild">这里是居中的子元素</div>
</div>
</body>
</html>
2.计算法
介绍:外层div相对定位,内层div相对定位
子容器相对定位 top:50%,translateY(-50%)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css">
html,body{
margin: 0; padding: 0;
}
.divParent {
position:relative;
width:600px;
height:400px;
background:#ddd;
margin: 0 auto;
}
.divChild {
position:relative;
top:50%;
margin:auto;
transform:translateY(-50%);
-ms-transform:translateY(-50%); /* IE 9 */
-moz-transform:translateY(-50%); /* Firefox */
-webkit-transform:translateY(-50%); /* Safari 和 Chrome */
-o-transform:translateY(-50%); /* Opera */
background:green;
width:30%;
height:30%;
}
</style>
</head>
<body>
<div class="divParent">
<div class="divChild">这里是居中的子元素</div>
</div>
</body>
</html>
3.宽高固定值计算法
介绍:外层div相对定位,内层div绝对定位
宽高一定 top left 50% ,margin-top、margin-tleft宽高各一半
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css">
html,body{
margin: 0; padding: 0;
}
.divParent {
position:relative;
width:600px;
height:400px;
background:#ddd;
margin: 0 auto;
}
.divChild {
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div class="divParent">
<div class="divChild">这里是居中的子元素</div>
</div>
</body>
</html>
4.calc计算法
介绍:外层相对,内层绝对
top: calc(50% - (* px/2)),left: calc(50% - (* px/2));
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css">
html,body{
margin: 0; padding: 0;
}
.divParent {
position:relative;
width:600px;
height:400px;
background:#ddd;
margin: 0 auto;
}
.divChild {
position: absolute;
width: 200px;
height: 200px;
top: calc(50% - (200px/2));
left: calc(50% - (200px/2));
background: green;
}
</style>
</head>
<body>
<div class="divParent">
<div class="divChild">这里是居中的子元素</div>
</div>
</body>
</html>
注:以上是个人实际应用中使用的主要三种方法、网上还有各样方法提供