绝对定位居中

发布时间 2023-12-20 22:33:01作者: Ewar-k

绝对定位居中

  • 设置水平居中 先设置子元素左侧移动到水平中心位置 left: 50%; , 再设置 margin-left: -40px 向左移动 40 像素 ;
/* 绝对定位元素 - 水平居中 */
.top {
    /* 子元素设置绝对定位 父元素需要设置相对定位 */
    position: absolute;
    /* 该盒子在父容器左上角 */
    /* 上边偏移 0 紧贴顶部 */
    top: 0;
    /* 左边偏移 50% 左侧紧贴水平居中位置 */
    left: 50%;

    /* 再向做移动 40 像素, 水平居中 */
    margin-left: -40px;

    /* 内容尺寸 */
    width: 80px;
    height: 80px;

    background-color: blue;
}
  • 设置垂直居中 : 先设置子元素顶部移动到父容器垂直中心位置 top: 50%; , 然后再向上移动 40 像素 ;
/* 绝对定位元素 - 垂直居中 */
.bottom {
    /* 子元素设置绝对定位 父元素需要设置相对定位 */
    position: absolute;
    /* 该盒子在父容器右下角 */
    /* 顶部移动到垂直中心位置 */
    top: 50%;
    /* 右边偏移 0 紧贴右侧 */
    right: 0;

    /* 垂直方向上 , 再向上走 40 像素 使得垂直居中 */
    margin-top: -40px;

    /* 内容尺寸 */
    width: 80px;
    height: 80px;

    background-color: red;
}

完整示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>绝对定位示例</title>
        <style>
            /* 最外层 父容器盒子 */
            .box {
                /* 子元素设置绝对定位 父元素需要设置相对定位 */
                position: relative;

                /* 内容尺寸 通过测量图片获得 */
                width: 300px;
                height: 200px;

                /* 边框 1 像素实线 */
                border: 1px solid #ccc;
                /* 上下设置 100 像素外边距 水平居中 */
                margin: 100px auto;
                /* 子元素与 */
                padding: 10px;

                background-color: pink;
            }

            /* 标准流元素 */
            .center {
                width: 300px;
                height: 200px;

                background-color: purple;
            }

            /* 绝对定位元素 - 水平居中 */
            .top {
                /* 子元素设置绝对定位 父元素需要设置相对定位 */
                position: absolute;
                /* 该盒子在父容器左上角 */
                /* 上边偏移 0 紧贴顶部 */
                top: 0;
                /* 左边偏移 50% 左侧紧贴水平居中位置 */
                left: 50%;

                /* 再向做移动 40 像素, 水平居中 */
                margin-left: -40px;

                /* 内容尺寸 */
                width: 80px;
                height: 80px;

                background-color: blue;
            }

            /* 绝对定位元素 - 垂直居中 */
            .bottom {
                /* 子元素设置绝对定位 父元素需要设置相对定位 */
                position: absolute;
                /* 该盒子在父容器右下角 */
                /* 顶部移动到垂直中心位置 */
                top: 50%;
                /* 右边偏移 0 紧贴右侧 */
                right: 0;

                /* 垂直方向上 , 再向上走 40 像素 使得垂直居中 */
                margin-top: -40px;

                /* 内容尺寸 */
                width: 80px;
                height: 80px;

                background-color: red;
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div class="top"></div>
            <div class="center"></div>
            <div class="bottom"></div>
        </div>
    </body>
</html>