CSS 垂直居中布局

下面都是我在网上借鉴的方法,亲测可用。

//父元素
//子元素

第一种: 定位
规则如下:
1、父元素为除了static以外的定位方式;
2、子元素为绝对定位,top、bottom、left和right 均设置为0,margin设置为
auto。
代码如下:

.fStyle {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px solid red;
}
.cStyle {
    position: absolute;
    width: 50px;
    height: 50px;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
    border: 1px solid green;
}

第二种: flex布局
规则如下:align-items实现垂直居中,justify-content实现水平居中。
代码如下:

.fStyle {
    width: 100px;
    height: 100px;
    border: 1px solid red;
    display: flex;
    align-items: center;
    justify-content: center;
}
.cStyle {
    width: 50px;
    height: 50px;
    border: 1px solid green;
}

第三种: table-cell布局
规则如下:
1、父布局使用vertical-align: middle实现垂直居中,
2、子布局使用margin: 0 auto实现水平居中。
代码如下:

.fStyle{
    width: 100px;
    height: 100px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
}
.cStyle{
    width: 50px;
    height: 50px;
    border: 1px solid green;
    margin: 0 auto;
}

第四种: translate+relative定位
规则如下:
1、子组件采用relative 定位;
2、top和left偏移各为50%;
3、translate(-50%,-50%) 偏移自身的宽和高的-50%。
代码如下:

.fStyle {
    width: 100px;
    height: 100px;
    border: 1px solid red;
}
.cStyle {
    width: 50px;
    height: 50px;
    border: 1px solid green;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

你可能感兴趣的:(CSS 垂直居中布局)