垂直水平居中总结

29 阅读1分钟

1,flex或者grid布局(可用于未知子元素宽高)

.box{
        width: 500px;
        height: 500px;
        border: 1px solid #000;
        display: flex;
        }
        .content{
        margin: auto;
        }
.box {
            width: 500px;
            height: 500px;
            border: 1px solid #000;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .content {
            border: 1px solid #000;
        }

2,绝对定位+translate(可用于未知子元素宽高)

.box {
            width: 500px;
            height: 500px;
            border: 1px solid #000;
            position: relative;
        }
        .content {
            border: 1px solid #000;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

3,绝对定位+0偏移量(必须已知子元素宽高)

.box{
        width: 500px;
        height: 500px;
        border: 1px solid #000;
        position: relative;
        }
        .content{
        width: 100px;
        height: 100px;
        border: 1px solid #000;
        position: absolute;
        top: 0;bottom: 0;left: 0;right: 0;
        margin: auto;
        }

4,绝对定位+负margin

.box {
            width: 500px;
            height: 500px;
            border: 1px solid #000;
            position: relative;
        }
        /*已知原素宽高,margin偏移一半*/
        .content {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px;
            margin-left: -50px;
        }

5,行内元素(行内块元素)可使用line-height=height,margin=0 auto,比较简单