將要設置居中的元素上 、右、下、左 都設爲0,再將margin值設爲水平垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.main{
/*必須有position:relative;*/
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
.content{
/*必須有position:absolute;*/
position: absolute;
left: 0;
top: 0;
right: 0;
bottom:0;
margin: auto;
background-color: blue;
width:20px;
height: 20px;
}
</style>
</head>
<body>
<div class="main">
<div class="content"></div>
</div>
</body>
</html>
方法二:設置top和left爲50%,再設置margin-top和left爲負值(自己的一半)
.content{
/*必須有position:absolute;*/
position: absolute;
top: 50%;
left: 50%;
width:20px;
height: 20px;
margin-top: -10px;
margin-left: -10px;
background-color: blue;