水平 margin auto
margin: 0 auto;原理:当 margin 值为 auto 时,元素会尝试占据尽可能大的空间。比如,margin-left 会让 div 尽量靠最右侧。
margin: 0 auto; 相当于垂直margin: 0的同时,让 margin-left: auto 和 margin-right: auto,所以把盒子挤在水平居中位置。
flex 布局
display: flex;
justify-content: center;绝对定位
.parent {
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
/*
或者:
1. transform: translateX(-50px) translateY(-50px);
2. left: calc(50% - 50px); right: calc(50% - 50px)
*/
}
弹性盒子
display: flex;
align-items: center