首页 > Web开发 > 详细

Css的几种实现水平垂直居中方式

时间:2020-11-06 15:56:19      阅读:40      评论:0      收藏:0      [点我收藏+]

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(css新出的网格布局)

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

Css的几种实现水平垂直居中方式

原文:https://www.cnblogs.com/yxkNotes/p/13936976.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!