常用的块级元素的水平垂直居中CSS方法(5种)
方法一:grid:网格布局
给父元素设置:display:grid
给子元素设置:align-self:center; justify-self:center;
#box{
background-color: aquamarine;
width: 500px;
height: 500px;
display: grid;
}
#boxSon{
background-color: rgb(211, 184, 49);
width: 200px;
height: 200px;
align-self: center;
justify-self: center;
}
方法二: 弹性盒子
只需要给父元素设置:
display:flex;
justify-content:center;
align-items:center;
#box {
background-color: aquamarine;
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
}
#boxSon {
background-color: rgb(211, 184, 49);
width: 200px;
height: 200px;
}
方法三: 绝对定位+负margin
需知道子元素盒子大小:margin=负盒子宽度的一半
#box {
background-color: aquamarine;
width: 500px;
height: 500px;
position: relative;
}
#boxSon {
background-color: rgb(211, 184, 49);
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin: -100;
}
方法四: 绝对定位+margin
不需知道子元素盒子大小
#box {
background-color: aquamarine;
width: 500px;
height: 500px;
position: relative;
}
#boxSon {
background-color: rgb(211, 184, 49);
width: 200px;
height: 200px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法五: 绝对定位+过渡
不需要子元素固定宽高
子:top: 50%;
left: 50%;
transform:translate(-50%, -50%)
#box {
background-color: aquamarine;
width: 500px;
height: 500px;
position: relative;
}
#boxSon {
background-color: rgb(211, 184, 49);
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}