垂直水平居中方法总结

287

今天老大随口问了这个问烂了的问题,我只回答了两种,好吧,还是老老实实总结下来加强下记忆吧。


一:定位+边距(固定宽高度适用)

<div class="container">
    <div class="inner"></div>
</div>
.container {
    width: 400px;
    height: 400px;
    position: relative;
    background-color: yellow;
}

.inner {
    position: absolute;
    height: 200px;
    width: 200px;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
    background-color: red;
}

二:定位+transform(不固定宽高也适用)

.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    position: relative;
}

.inner {
    height: 200px;
    width: 200px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

三:flex布局

.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    display: flex;
    align-items: center;
    justify-content: center;
}

.inner {
    height: 200px;
    width: 200px;
    background-color: red;
}

四:table布局

 <div class="container">
    <div class="outter">
        <div class="inner"></div>
    </div>
</div>
.container {
    width: 400px;
    height: 400px;
    background-color: yellow;
    display: table;
}

.outter {
    background-color: red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.inner {
    height: 100px;
    width: 100px;
    display: inline-block;
    background-color: white;
}

五:杂谈

以上为比较好用的块级元素居中方案,别的一些细节如下:

行内元素垂直居中:

1、父元素等值padding

2、子元素line-height等于父元素高度

块级元素水平居中:

margin: 0 auto

基础还是要打好的,知道不行,熟练也不够,希望刻在脑子里,形成条件反射才足够。