在css的应用中,让子盒子在父盒子里面水平垂直居中我们有三种方法:
首先我们需要先创建两个盒子,再给盒子添加css属性;
第一种:
.box1 {
/* 相对定位 */
position: relative;
width: 600px;
height: 600px;
background-color: pink;
}
.box2 {
/* 绝对定位 */
position: absolute;
/* 第一步: 先将子盒子向上及向左移动父盒子的50%;*/
top: 50%;
left: 50%;
/* 第二步:再让子盒子移动自身宽高的一般半*/
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: blue;
}
第二种:
.box1 {
/* 相对定位 */
position: relative;
width: 600px;
height: 600px;
background-color: pink;
}
.box2 {
/* 绝对定位 */
position: absolute;
/* 将子盒子的上右下左四个属性都设置为0 */
top: 0;
right: 0;
bottom: 0;
left: 0;
/* 再将盒子外边距设置为auto */
margin: auto;
width: 200px;
height: 200px;
background-color: blue;
}
第三种:
.box1 {
/* 相对定位 */
position: relative;
width: 600px;
height: 600px;
background-color: pink;
}
.box2 {
/* 绝对定位 */
position: absolute;
/* 第一步: 先将子盒子向上及向左移动父盒子的50%; */
top: 50%;
left: 50%;
/*第二步: 使用 transform位移 值为百分比时:参照自身宽高;
值为px时:参照父盒子宽高移动 */
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: blue;
}