问:说一下让盒子水平/垂直居中的几种方
方法一:
1. 父元素设置display : flex ;
2. 然后通过justifly-content : center ; 进行主轴居中
3. 最后align-item : center ; 进行侧轴居中
.fater{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
} .fater {
display: flex;
width: 600px;
height: 600px;
background-color: skyblue;
/* 主轴居中 */
justify-content: center;
/* 侧轴居中 */
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: blueviolet;
}
方法二:父元素设置相对定位 , 子元素设置绝对定位 子绝父相
.fater{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
}
/* 子绝父相+margin */
.son{
position: absolute;
width: 200px;
height: 200px;
background-color: blueviolet;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
}
方法三:父元素设置相对定位 , 子元素设置绝对定位 子绝父相 使用盒子位移实现
.fater{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
}
.son{
position: absolute;
width: 200px;
height: 200px;
background-color: blueviolet;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
方法四:父元素设置相对定位 , 子元素设置绝对定位 子绝父相 使用盒子定位实现
.fater{
position: relative;
width: 600px;
height: 600px;
background-color: skyblue;
}
.son{
position: absolute;
width: 200px;
height: 200px;
background-color: blueviolet;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}