美文网首页
CSS实现垂直居中的N种方式

CSS实现垂直居中的N种方式

作者: Rudy_Ran | 来源:发表于2019-11-02 11:06 被阅读0次

准备工作

准备阶段的基础代码如下:

<div class="parent">
       <div class="child">Hello World</div>
 </div>


.parent{
      border: 1px solid black;
      width: 400px;
      height: 400px;
 }
.child{
            background: pink;
      width: 150px;
      height: 150px;
}

实现垂直居中的方式

1. 定位+负margin

.parent{
        position: relative;
    }
    .child{
        position:absolute;
        top: 50%;
        left: 50%;
        margin-top: -75px;
        margin-left: -75px;
    }

2. 定位+margin auto

.parent{
        position: relative
    }
    .child{
        position:absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
    }

3. 定位+calc

.parent{
        position: relative;
    }
    .child{
        position:absolute; 
        top: calc(50% - 75px);
        left: calc(50% - 75px);
    }

4. 定位+ transform

.parent{
        position: relative;
    }
    .child{
        position:absolute; 
        top: 50%;
        left:50%;
        transform: translate(-50%,-50%);
    } 

5. lineheight方式

当一个box为行内元素时,通过text-align就可以做到水平居中,垂直方向采用vertical-algin实现居中

.parent{
        line-height: 400px;
        text-align: center;
    }
    .child{
        display: inline-block;
        vertical-align: middle;
    }

6. css-table属性

.parent{
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    .child{
        display: inline-block; 
    }

7. flex布局

.parent {
                display: flex;
            justify-content: center;
            align-items: center;
    }

8. grid布局

和grid差不多的一种方式,但兼容性不如flex

.parent {
        display: grid;
    }

    .child {
        align-self: center;
        justify-self: center;
   }

以上基本上就是一些常见的水平居中方式,一般来说:

  • 定位方式+负margin兼容性最好,但是需要宽高固定
  • 最简单的方式是flex和grid,但兼容性不友好,grid不如flex方式
  • 移动端对于flex的兼容性很好
方法 是否需要知道元素宽高
定位+负margin
定位+margin auto
定位+ calc
定位+ transform
lineheight
css-table
flex
grid

相关文章

网友评论

      本文标题:CSS实现垂直居中的N种方式

      本文链接:https://www.haomeiwen.com/subject/kkucbctx.html