css实现水平垂直居中

1.居中元素定宽高其中像素都代表居中元素高度的一半

    absolute + 负margin

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

    absolute + margin auto

.children{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

    absolute + calc

.children{
    position: absolute;
    top:  calc(50% - 50px);
    left: calc(50% - 50px);
}

2.居中元素不定宽高

    absolute + transfrom

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

    line-height(把children设为行内元素,通过text-align就可以做到水平居中,使用vertical-align也可以在垂直方向做到居中。)

.parent{
    line-height: 400px;
    text-align: center;
    font-size: 0px;
}
.children{
    font-size: 16px;
    display: inline-block;
    vert-align: middle;
    line-height: initial;
    text-align: left;
}

    writing-mode(writing-mode可以改变文字的显示方向,比如可以改变writing-mode让文字的显示变为垂直方向。)

.parent{
    writing-mode: vertical-lr;
    text-align: center;
}
.parent-inner{
    writing-mode: horizontal-tb;
    display: inline-block;
    text-align: center;
    width: 100%;
}
.children{
    display: inline-block;
    margin: auto;
    text-align: left;
}

     css-table

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

    flex

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

    grid

.parent{
    display: grid;
}
.children{
    align-self: center;
    justify-self: center;
}

  后续补充------

posted @ 2020-11-06 15:09  Judicious  阅读(256)  评论(0编辑  收藏  举报