div垂直居中(常用5种方法)

思路:父元素position: relative; 子元素通过position: absolute;定位到居中。

结构与基础css(父元素position: relative;)

    <div class="app">
        <div class="box">box</div>
    </div>
    
    .app{
        height: 300px;
        background-color: gray;
        position: relative;
    }
    .box{
        width: 100px;
        height: 100px;
        background-color: red;
    }

方法一

    .box{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -50px;
    }

方法二

    .box{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
    }

方法三

    .box{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
        top: calc(50% - 50px);
    }

方法四

    .box{
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto 0;
    }

方法五

利用flex布局,简单快速实现

    .app{
        display: flex;
        align-items: center;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。