CSS 水平垂直居中 9 种方法

您所在的位置:网站首页 css各种居中 CSS 水平垂直居中 9 种方法

CSS 水平垂直居中 9 种方法

2023-07-03 12:22| 来源: 网络整理| 查看: 265

一、水平垂直居中 9 种方法汇总 有哪些方法?

父、子元素宽高未知时

table-cell(使用表格样式) flex 布局(父级 justify-content: center 和 align-items: center 即可) absolute + transform(定位的上、左为 50%,translate 上、左负 50%) absolute + margin: auto(定位的上下左右为 0) Grid 网格布局 直接使用 table(改变结构实现,和第一条类似)

子元素固定宽高已知时(假设子元素宽高为 200px)

absolute + calc(定位上、左负50%时减去子元素宽、高) absolute + 负margin(定位的上、左为 50%,margin 的上、左负子元素的一半)

父元素高度已知(假设为 400px),子元素宽高未知

text-align + vertical-align 初始化测试代码

HTML 测试代码,默认父子元素宽高未知。

           Demo                 .parent {     width: 100%;     height: 50%;     background-color: skyblue;   }   .children {     width: 20%;     height: 20%;     background-color: pink;   }    复制代码 二、父、子元素宽高未知(6 种) 第一种:table-cell .parent {   display: table-cell;   text-align: center;   vertical-align: middle; } .children {   display: inline-block; } 复制代码 第二种:flex 布局(两种办法)

① 只设置父元素

.parent {   display: flex;   justify-content: center;   align-items: center; } 复制代码

② 同时设置父子元素

.parent {   display: flex; } .children {   align-self: center;   margin: auto; } 复制代码 第三种:absolute + transform .parent {   position: relative; } .children {   position: absolute;   top: 50%;   left: 50%;   transform: translate(-50%, -50%); } 复制代码 第四种:absolute + margin: auto .parent {   position: relative; } .children {   position: absolute;   top: 0;   left: 0;   right: 0;   bottom: 0;   margin: auto; } 复制代码 第五种:Grid 布局 .parent {   display: grid; } .children {   align-self: center;   justify-self: center; } 复制代码 第六种:直接使用 table(改变结构实现,和第一条类似)

HTML 代码

     复制代码

CSS 代码

.parent {   text-align: center; } .children {   display: inline-block; } 复制代码 三、子元素宽高已知(假设子元素宽高为 200px) 第一种:absolute + calc .parent {   position: relative; } .children {   position: absolute;   top: calc(50% - 100px);   left: calc(50% - 100px); } 复制代码 第二种:absolute + 负 margin .parent {   position: relative; } .children {   position: absolute;   top: 50%;   left: 50%;   margin-top: -100px;   margin-left: -100px; } 复制代码 四、父元素高度已知(假设为 400px),子元素宽高未知 第一种:text-align + vertical-align .parent {   text-align: center;   line-height: 400px; } .children {   display: inline-block;   vertical-align: middle;   line-height: initial; } 复制代码


【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3