方法1-绝对位移居中
1 让子盒子移动父元素的一半(往右) left: 50%; /*让子盒子移动父元素的一半(往下) */ top: 50%;
/* 2 在让子盒子往左移动自身宽度的一半 使用margin负值 / / 普通做法 */ margin-left: -150px;
/* 在让子盒子往上移动自身高度的一半 使用margin负值 */ margin-top: -100px;
方法2 位移-绝对定位居中
.box1 { position: relative; width: 300px; height: 300px; background-color: pink; }
.box2 {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
background-color: purple;
transform: translate(-50%, -50%);
}
方法3 -绝对定位居中
.box1 { position: relative; width: 300px; height: 300px; background-color: pink; } /* 了解即可 / / .box2 { position: absolute; left: 0; top: 0; bottom: 0; right: 0; width: 100px; height: 100px; background-color: purple; margin: auto; } */
方法4 -flex布局居中
justify-content: center; align-items: center;