如何在一个不定宽高的盒子中垂直居中

130 阅读1分钟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

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

        .parent {
            width: 40%;
            height: 30%;
            background: bisque;
            position: relative;
            margin: 2%;
        }

        .child {
            height: 30%;
            width: 30%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: red;
        }

        .parent1 {
            width: 40%;
            height: 30%;
            background: bisque;
            position: relative;
            margin: 2%;
        }

        .child1 {
            height: 30%;
            width: 30%;
            background: red;
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            top: 0;
            margin: auto;
        }

        .parent3 {
            width: 40%;
            height: 30%;
            background: bisque;
            display: flex;
            flex-flow: row wrap;
            align-items: center;
            justify-content: center;
            margin: 2%;
        }

        .child3 {
            height: 30%;
            width: 30%;
            background: red;
        }
    </style>
</head>
<body>
<div class='parent'>
    <div class='child'>cccc</div>
</div>
<div class='parent1'>
    <div class='child1'>ddddd</div>
</div>
<div class='parent3'>
    <div class='child3'>eeee</div>
</div>
</body>
</html>