1、父元素开启相对定位,子元素开启绝对定位,子元素中margin减去自身宽高的一半。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin:0;
padding:0;
}
#outer {
position:relative;
margin:10px auto;
width:300px;
height:300px;
background-color:skyblue;
}
.inner {
position:absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
width:100px;
height:100px;
background-color:plum;
}
</style>
</head>
<body>
<div id="outer">
<div class="inner"></div>
</div>
</body>
</html>
2、子元素相对于父元素绝对定位,并且margin值为auto
该方式不受元素宽高所限制,比较好用(推荐使用)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin:0;
padding:0;
}
#outer {
position:relative;
margin:10px auto;
width:300px;
height:300px;
background-color:skyblue;
}
.inner {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
width:100px;
height:100px;
background-color:plum;
}
</style>
</head>
<body>
<div id="outer">
<div class="inner"></div>
</div>
</body>
</html>
3、将元素转换成表格样式:diplay:table-cell,再利用表格的样式来进行居中(推荐)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin:0;
padding:0;
}
#outer {
display:table-cell;
vertical-align:middle;
width:300px;
height:300px;
background-color:skyblue;
}
.inner {
margin:auto;
width:100px;
height:100px;
background-color:plum;
}
</style>
</head>
<body>
<div id="outer">
<div class="inner"></div>
</div>
</body>
</html>
4、父元素开启相对定位,子元素开启绝对定位,在子元素中设置tranform属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin:0;
padding:0;
}
#outer {
position:relative;
margin:10px auto;
width:300px;
height:300px;
background-color:skyblue;
}
.inner {
position:absolute;
top:50%;
left:50%;
width:100px;
height:100px;
background-color:plum;
transform:translate(-50%,-50%);
}
</style>
</head>
<body>
<div id="outer">
<div class="inner"></div>
</div>
</body>
</html>
5、在父元素中使用css3中的flex属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
margin:0;
padding:0;
}
#outer {
display:flex;
justify-content:center;
align-items:center;
margin:10px auto;
width:300px;
height:300px;
background-color:skyblue;
}
.inner {
width:100px;
height:100px;
background-color:plum;
}
</style>
</head>
<body>
<div id="outer">
<div class="inner"></div>
</div>
</body>
</html>