水平垂直居中

水平垂直居中是最常用到的布局,那么常用的解决方案都有哪些呢,下面就依次来列举一下

例子:

HTML代码:

<div class="container">
    <div class="inner">内容</div>
</div>

常用解决方案类别:

一.脱离文档流方式的居中

  1. 负margin的方式(inner宽高知道)

.container{
    position: relative;
}
.inner{
    width:100px;
    height:30px;
    position: absolute;
    top:50%;
    left:50%;
    margin-top:-15px;
    margin-left:-50px;
}

2.transform:translate的方式

.inner{
    width:100px;
    height:30px;
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
}

3.margin:auto的方式

4.css3的 calc属性方式(固定高度

<div class="container">Hello World!</div>

.container {
    position: absolute;
    width: 300px;
    height: 300px;
    left: calc(50% - 150px);
    top: calc(50% - 150px);
    border: 1px solid red;
}

二.未脱离文档流方式的居中

1.line-height方式实现(固定高度)

<div class="container">Hello World!</div>

.container {
    width: 300px;
    height: 300px;
    line-height: 300px;
    text-align: center;
    border: 1px solid red;
}

2.flex布局

.container {
    display: flex;
    height: 100vh;
}

.inner {
    margin: auto;
}
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

3.table方式

.container {
    display: table;         /* 让div以表格的形式渲染 */
    width: 100%;
    border: 1px solid red;
}

.inner {
    display: table-cell;    /* 让子元素以表格的单元格形式渲染 */
    text-align: center;
    vertical-align: middle;
}

Last updated

Was this helpful?