元素水平垂直居中方法
方案一、弹性盒子沿主轴和侧轴居中
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
justify-content: center;
align-items: ceter;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
}
方案二、弹性盒子设置自动的边距
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
margin: auto;
}
方案三、定位设置子元素左上角位于父元素中心,然后通过translate参考自身宽高,分别移动-50%
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)
}
方案三、通过margin计算上下边距设置垂直居中,然后用auto实现水平居中
.outer {
width: 400px;
height: 400px;
background-color: #888;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
margin: 150px auto;
}
方案四、类似方案二,设置上下左右距离都是0,然后设置auto的边距
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
方案五、类似方案三,先将子元素左上角定位到父元素中心,然后利用margin参考自身宽高,分别左移和上移50%
.outer {
width: 400px;
height: 400px;
background-color: #888;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
标签:居中,color,100px,height,width,background,400px,CSS,大全
From: https://www.cnblogs.com/gin49sz/p/18117379