水平垂直居中
1、定位
.parent{
position: relative
}
.child{
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px; // 已知宽高
// transform: translate(-50%,-50%); // 未知宽高
}
2、flex
.parent {
width: 300px;
height: 300px;
/* flex布局 */
display: flex;
/* 使子项目水平居中 */
justify-content: center;
/* 使子项目垂直居中 */
align-items: center;
}
.child {
width: 100px;
height: 100px;
}
<div class="parent">
<div class="child"></div>
</div>
3、table-cell(不推荐)
水平居中
1、margin和width(已知宽)
div{
width:1000px;
margin: 0 auto;
}
2、绝对定位(已知宽)
.ele {
position: absolute;
width: 宽度值;
left: 50%;
margin-left: -(宽度值/2);
}
3、inline-block(未知宽)
父元素设置:
parent{
text-align: center;
}
child{
display: inline-block;
}
4、float + position: relative + left: 50%

image.png
6、Flex
垂直居中
1、绝对定位
水平垂直居中的基础上去掉
margin-left: -xx;
已知自元素宽高
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 150px;
height: 100px;
background: orange;
position: absolute;
top: 50%;
margin-top: -50px;
}
<div id="box">
<div id="child"></div>
</div>
未知子元素宽高
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
background: orange;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
</style>
<div id="box">
<div id="child">11</div>
</div>
2、flex
#box {
width: 300px;
height: 300px;
background: #ddd;
display: flex;
/* 垂直居中 */
align-items: center;
}
#child {
width: 150px;
height: 100px;
background: orange;
}
<div id="box">
<div id="child"></div>
</div>