方法一:position+margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="content"></div>
</div>
</body>
</html>
方法二:position+transform
.box{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
方法三:position+margin(需要知道子元素宽高)
.box{
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
方法四: flex
.box{
width: 200px;
height: 200px;
background-color: green;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
}
方法五: position+calc
.box{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: calc(50% - 50px);
left:calc(50% - 50px);
}
方法六:line-height+vertical-align
.box{
width: 200px;
height: 200px;
background-color: blue;
line-height: 200px;
text-align: center;
}
.content{
width: 100px;
height: 100px;
background-color: pink;
display: inline-block;
vertical-align: middle;
}