水平垂直居中的四种写法

110 阅读1分钟

全文使用同一个如下的html代码

    <div id="box-outer">
        <div id="box-inside"></div>
    </div>

写法一: 容器的height属性与line-height属性一致

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            line-height: 500px;
            text-align: center;
        }
        #box-inside {
            vertical-align: middle;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
        }

由于"幽灵元素"的存在,这个CSS实现的并不是绝对的垂直居中

加一段font-size: 0px; 到box-outer即可解决

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            line-height: 500px;
            text-align: center;
            
            font-size: 0px;
            
        }
        #box-inside {
            vertical-align: middle;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
        }

写法二: 使用绝对定位且margin设置为auto

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            position: relative;
        }
        #box-inside {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            width: 100px;
            height: 100px;
            background-color: blue;
        }

写法三 : 使用绝对定位配合使用margin/tarnsform

配合margin

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            position: relative;
        }
        #box-inside {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -50px;
            margin-left: -50px;
            width: 100px;
            height: 100px;
            background-color: blue;
        }

配合tansform

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            position: relative;
        }
        #box-inside {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 100px;
            height: 100px;
            background-color: blue;
        }

两者区别

使用margin需要知道元素的宽度和高度才能准确设置,而transform则是根据当前元素的宽度和高度百分比进行计算,不需要知道宽高即可居中。个人偏向于后者

写法四: flex布局

        #box-outer {
            width: 100%;
            height: 500px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #box-inside {
            width: 100px;
            height: 100px;
            background-color: blue;
        }