美文网首页前端开发
垂直居中的实现方法

垂直居中的实现方法

作者: 曼木子 | 来源:发表于2020-06-29 23:38 被阅读0次

    第一种 absolute + margin:auto 未知居中元素宽高

    .parent {
        position: relative;
    }
    .child {
        position: absolute;;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
    

    第二种 absolute + transform 未知居中元素宽高

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

    第三种 flex 未知居中元素宽高

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

    第四种 absolute + calc 已知居中元素的宽高为100px

    .parent {
        position: relative;
    }
    .child{
        position: absolute;;
        width:100px;
        height:100px;
        top: calc(50% - 50px);
        left: calc(50% - 50px);
    }
    
    

    第五种 absolute + 负的margin 已知居中元素的宽高为100px

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

    第六种 line-height + inline-block + vertical-align 未知居中元素宽高

    .parent{
        line-height: 600px;
        text-align: center;
    }
    .child{
        display: inline-block;
        vertical-align: middle;
        line-height: initial;   
    }
    

    相关文章

      网友评论

        本文标题:垂直居中的实现方法

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