【八股】未知宽高元素水平垂直居中的三种方法

在笔试/面试中,经常出现的一个问题就是:如何实现元素水平垂直居中?

本文会直接使用代码,介绍未知宽高元素水平垂直居中的三种方法:

方法一:绝对定位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 {
    /* 不需要设置宽高 */
}

欢迎指正!

相关推荐
C+++Python20 小时前
如何使用CSS Grid?
css
三七吃山漆20 小时前
攻防世界——wife_wife
前端·javascript·web安全·网络安全·ctf
用户479492835691520 小时前
面试官问"try-catch影响性能吗",我用数据打脸
前端·javascript·面试
GISer_Jing21 小时前
前端营销技术实战:数据+AI实战指南
前端·javascript·人工智能
嘉琪00121 小时前
Vue3+JS 高级前端面试题
开发语言·前端·javascript
vipbic1 天前
用 Turborepo 打造 Strapi 插件开发的极速全栈体验
前端·javascript
天涯学馆1 天前
为什么 JavaScript 可以单线程却能处理异步?
前端·javascript
Henry_Lau6171 天前
主流IDE常用快捷键对照
前端·css·ide
C+++Python1 天前
CSS Grid和Flexbox有什么区别?
css
asdfg12589631 天前
JS中的闭包应用
开发语言·前端·javascript