目录
效果图如下:
初始化盒子
.father {
width: 600px;
height: 400px;
border: 3px solid rgb(31, 72, 183);
.box {
width: 200px;
height: 200px;
background-color: rgb(247, 118, 19);
}
}
1. 固定定位
.box {
position: fixed;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
2. 父元素flex布局
.father {
display: flex;
justify-content: center;
align-items: center;
}
3. 子绝父相— margin设置为auto
.father {
display: relative;
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
}
4. 子绝父相— transform
.father {
display: relative;
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
}
5. 父元素 table-cell 布局
.father {
width: 500px;
height: 500px;
display: table-cell;
vertical-align: middle;
.box {
margin: 0 auto;
}
}
6. 子元素 inline-block
.father {
width: 500px;
height: 500px;
line-height: 500px;
text-align: center;
.box {
display: inline-block;
vertical-align: middle;
}
}