固定宽高
1.position+margin-top+margin-left
.box-container{
position: relative;
width: 300px;
height: 300px;
}
.box-container .box {
width: 200px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px; /* 高度的一半 */
margin-left: -100px; /* 宽度的一半 */
}
2.position+margin
.box-container{
position: relative;
}
.box-container .box{
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
未知宽高
1.transform 在子元素上设置 transform详解
transform: translate(-50%, -50%); 用于平面的2D转换,后面的百分比以自身的宽高为参考,定位后将元素的左上角置于父级中央,之后再用 transform 进行偏移,相当于上面设置的 margin-top 和 margin-left
.box-container {
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.flex布局 在父级设置 弹性盒子详解
justify-content: center;把弹性项沿着弹性容器的主轴线(main axis)对齐。
align-items: center; 设置弹性盒子元素在侧轴(纵轴)方向上的对齐方式
.box-container {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
justify-content: center;
align-items: center;
}
3.display: table-cell 无兼容性问题
.box-container {
position: relative;
width: 500px;
height: 500px;
border: 1px solid red;
display: table-cell;
text-align: center;
vertical-align: middle;
}