美文网首页让前端飞
CSS的水平垂直居中

CSS的水平垂直居中

作者: 阿毛啊726 | 来源:发表于2020-06-11 17:49 被阅读0次

1)inline元素 :line-height的值为height值 text-align:center
2)absolute元素:top 50%+margin-top 负值(需要知道子元素尺寸)left 50%+margin-left 负值

.out{
        position: relative;
    }
.inner{
            width: x px
                height:y px
                position: absolute;
        top: 50%;
        left: 50%;//父亲的50%
        margin-left: x/2 px
                margin-top: y/2 px
    }

3)absolute元素:top 50% left 50% transform(-50%,-50%)(对兼容性有要求)

.out{
        position: relative;
    }
.inner{
        position: absolute;
        top: 50%;
        left: 50%;//父亲的50%
        transform: translate(-50%, -50%);//自己的50%
    }

4)absolute元素:top,left,bottom,right=0+margin:auto(不需要知道元素尺寸,对浏览器兼容性没有要求)

.out{
        position: relative;
     }
.inner{
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
     }

5)flex弹性布局

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

相关文章

网友评论

    本文标题:CSS的水平垂直居中

    本文链接:https://www.haomeiwen.com/subject/nkfitktx.html