在笔试/面试中,经常出现的一个问题就是:如何实现元素水平垂直居中?
本文会直接使用代码,介绍未知宽高元素水平垂直居中的三种方法:
方法一:绝对定位absolute
css
//绝对定位,将元素的左右位置设置为50%,平移自身高度的50%
//兼容性好、广泛使用
.absolute-center-container {
position: relative; /* 父容器设置为相对定位 */
height: 100%; /* 父容器高度 */
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 不需要设置宽高 */
}
方法二:flex布局
css
//设置父级为弹性盒子--简洁但是ie 11以上支持
.flex-container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 100%; /* 父容器高度 */
}
.centered {
/* 不需要设置宽高 */
}
方法三:grid布局
css
//设置父级为网格元素--简洁,ie10以上支持
.grid-container {
display: grid;
place-items: center; /* 相当于同时设置 justify-items 和 align-items */
height: 100%; /* 父容器高度 */
}
.centered {
/* 不需要设置宽高 */
}
欢迎指正!