CSS——绝对定位居中的方法

74 阅读1分钟

    <div class="conter"></div>
    <style>
        .conter {
            width: 600px;
            height: 400px;
            border: 1px solid red;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -200px;
            /* 高度的一半 */
            margin-left: -300px;
            /* 宽度的一半 */
        }
    </style>

注意:这种方法有一个很明显的不足,就是需要提前知道元素的尺寸。否则margin负值的调整无法精确。此时,往往要借助JS获得

    <div class="conter"></div>
    <style>
        .conter {
            width: 600px;
            height: 400px;
            position: absolute;
            border: 1px solid red;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    </style>

使用transform代替margin. transform中translate偏移的百分比值是相对于自身大小的,可以这样实现css绝对定位居中

    <div class="conter"></div>
    <style>
        .conter {
            width: 600px;
            height: 400px;
            position: absolute;
            border: 1px solid red;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            /* 有了这个就自动居中了 */
        }
    </style>

margin:auto实现绝对定位元素的居中(上下左右均0位置定位;margin: auto)