目录

1. flex弹性盒子

2. 利用 相对定位 + translate

3. 利用绝对定位 + margin: auto;

4. 父标签添加弹性盒子,子标签外边距设为auto


1. flex弹性盒子

<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>
        .father {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 500px;
            height: 500px;
            border: 1px solid #ccc;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>

2. 利用 相对定位 + translate

<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 {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100px;
            height: 100px;
            background-color: pink;
            transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>

3. 利用绝对定位 + margin: auto;

<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 {
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>

4. 父标签添加弹性盒子,子标签外边距设为auto

<!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>
        * {
            padding: 0;
            margin: 0;
        }

        body,
        html {
            width: 100%;
            height: 100%;
        }

        .bigBox {
            display: flex;
            width: 100%;
            height: 100%;
        }

        .smallBox {
            width: 300px;
            height: 300px;
            background-color: pink;
            margin: auto;
        }
    </style>
</head>

<body>
    <div class="bigBox">
        <div class="smallBox">上下左右居中</div>
    </div>
</body>

</html>

原文链接:https://blog.csdn.net/qq_52845451/article/details/126574126

最后修改:2023 年 10 月 30 日
如果觉得我的文章对你有用,请随意赞赏