三种方法实现垂直水平居中详解

来源:互联网 发布:喷绘用什么软件 编辑:程序博客网 时间:2024/06/05 15:14

在前端布局中或者笔试面试中,经常会问到如何实现垂直水平居中。以下就是常用的三种解决方法。

使用弹性布局

display:flex

首先看看html布局

<div class="wrap">    <div class="content"></div></div>

.content通常是指需要垂直水平居中的元素

.wrap就是它的父元素

设置父元素display:flex成为一个弹性盒子

justify-content:center设置其子元素水平居中

align-items:center设置其子元素垂直居中

!!!这里是align-items不是align-content

关于弹性盒子的问题下一期详细讲解

CSS样式

.wrap{     display:flex;     justify-content:center;     align-items:center;     height: 200px;     background:#18587A;}.content{    width: 1000px;    height: 100px;    background:#FC624D;}

优点:支持响应式布局,不需要具体计算

缺点:对IE兼容性不是太好(辣鸡IE)

下面介绍第二种方法

使用绝对定位

position:absolute

设置其父元素为相对定位display:relative

设置子元素,也就是需要垂直居中的元素display:absolute

设置子元素left:50%,top:50%,这样子元素的左上角就移动到父元素的中心了

设置子元素margin-left: - 子元素宽度的一半margin-top: - 子元素高度的一半

注意margin取负数,这样子元素就实现垂直水平居中了

CSS

.wrap{        position: relative;        height: 200px;        background-color: yellow;    }.content{        position: absolute;        left: 50%;        top: 50%;        width: 100px;        height: 100px;        margin-left: -50px;        margin-top: -50px;        background-color: green;    }

优点:兼容性比较好,支持更多浏览器

缺点:需要计算子元素的宽度和高度(不使用LESS和SASS情况下)

最后介绍一种方法

使用table-cell

设置父元素display:table-cell

设置父元素vertical-align: middle实现内容垂直居中

设置父元素text-align: center实现内容水平居中

下面看看具体的代码

.wrap{    display: table-cell;    vertical-align: middle;    text-align: center;    height: 500px;    width: 200px;    background: red;    }.content{    display: inline-block;    width:100px;    height: 200px;    background-color: green;    }

完结