<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style type="text/css">
/常见的居中/
.father{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
position: relative;
}
.child{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
}
/负边距居中/
.father2{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
position: relative;
}
.child2{
width: 100px;
height: 100px;
background-color: blue;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
/弹性布局居中(未知宽高也可以)/
.father3{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
}
.child3{
width: 100px;
height: 100px;
background-color: blue;
}
/左右居中/
.father4{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
position: relative;
text-align: center;
}
.child4{
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
}
/很巧妙的方法/
.father5{
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
position: relative;
text-align: center;
}
.child5{
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
top:50%;
left:50%;
transform:translate(-50%,-50%);
position: absolute;
}
</style>
<body>
<div class="father">
<div class="child"></div>
</div>
<div class="father2">
<div class="child2">
</div>
</div>
<div class="father3">
<div class="child3">
</div>
</div>
<div class="father4">
<div class="child4">
</div>
</div>
<div class="father5">
<div class="child5">
</div>
</div>
</body>
</html>