子元素相对父元素居中

2022-03-10 15:45:02
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
            position: relative;
        }
        .inner {
            width: 150px;
            height: 150px;
            background-color: aqua;
            position: absolute;
            /* 先让子元素右移到父元素宽度的 50% */
            left: 50%;
            /* 再让子元素左移自身宽度的 50% */
            transform: translateX(-50%)
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="inner"></div>
    </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
            position: relative;
        }
        .inner {
            width: 150px;
            height: 150px;
            background-color: aqua;
            position: absolute;
            /* 先让子元素右移动父元素宽度的 50% */
            left: 50%;
            /* 再让子元素左移自身宽度的 50%,上移自身高度的 50%*/
            transform: translateX(-50%) translateY(-50%);
            /* 写法二 */
            /* transform: translate(-50%,-50%) translateY(-50%); */
            /* 让子元素向下移动父元素宽度的 50% */
            top: 50%;
            /* 如果单独在这里定义 transform 会覆盖上面的 transform 定义,所以要将 translateX 和 translateY 写在一行 */
            /* transform: translateY(-50%); */
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="inner"></div>
    </div>
</body>
</html>