记录水平垂直居中的多种方式和优缺点

前言

初级前端面试必考题,不少面试官都喜欢问这个问题。实习生的我面试遇到好几回了,在这里作一下总结。css

水平垂直居中元素宽高固定

1.absolute + 负margin
2.absolute + margin auto
3.absolute + calc
复制代码

水平垂直居中元素宽高不固定

1. absolute + transform
2. text-align + lineheight + vertical-align
3. css-table
4. flex
5. grid
复制代码

公共Html代码

<div class="parent">
    <div class="child"></div>
</div>
复制代码

公共Css样式

.parent{
    border: 1px solid cadetblue;
    width:300px;
    height:300px; 
}
.child{
   height: 100px;
   width: 100px;
   background: cornflowerblue;   
}
复制代码

1.absolute + 负margin

.child{
    height: 100px;
    width: 100px;
    background: cornflowerblue;     
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
复制代码

绝对定位的百分比是相对于父元素的宽高,top:50% left:50%是基于子元素的左上角偏移的,效果以下图:前端

在使用子元素的外边距为子元素宽高一半的负值进行相反方向偏移就能够让子元素居中了。css3

2.absolute + margin auto

.child{
    height: 100px;
    width: 100px;
    background: cornflowerblue;     
    position: absolute;
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
复制代码

设置各个方向的距离都是0,margin设为auto表明子元素到父元素上下、左右的距离相同,就能够实现水平垂直居中了。面试

3.absolute + calc

.child{
    height: 100px;
    width: 100px;
    background: cornflowerblue;     
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}
复制代码

css3的计算属性,top、left的百分比是基于元素的左上角偏移,那么在减去自身一半的宽高就行了。bash

4.absolute + transform

.child{
    height: 100px;
    width: 100px;
    background: cornflowerblue;     
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
复制代码

transform的translate属性也能够设置百分比,其是相对于自身的宽高,因此translate设置为(-50%,-50%),就能够作到水平垂直居中了。编辑器

5.text-align + lineheight + vertical-align

父元素添加样式布局

text-align: center;
 line-height: 300px;
复制代码

子元素添加样式flex

display: inline-block;
 vertical-align: middle;
复制代码

middle:元素上下边的中心点和行基线向上1/2x的高度位置对齐。url

图中的红线是我认为的行高基线(这个知识点不太熟...)spa

6.css-table

.parent{
        border: 1px solid cadetblue;
        width:300px;
        height:300px; 
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    .child{
        height: 100px;
        width: 100px;
        background: cornflowerblue;     
        display: inline-block;
    }
复制代码

7.flex

这是我最经常使用的一种方式,flex布局除了水平垂直居中外还有不少属性能够了解。

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

8.grid

css新出的网格布局 ,兼容性不太好。

.parent {
    display: grid;
}
.child {
    align-self: center;
    justify-self: center;
}
复制代码

总结

  1. PC端有兼容性要求,宽高固定,推荐absolute + 负margin
  2. PC端有兼容要求,宽高不固定,推荐css-table
  3. PC端无兼容性要求,推荐flex
  4. 移动端推荐使用flex
相关文章
相关标签/搜索