CSS implements a vertically centered display of boxes

The body content area

<body>
<div class="parent">
    <div class="child"></div>
</div>
</body>
Copy the code

Method 1: Using positioning (common)

<style>. Parent {/* parent box relative position */ position: relative; width: 300px; height: 300px; border: 1px solid #000; margin: 100px auto; } .child { width: 100px; height: 100px; border: 1px solid #999; background-color: skyblue; /* Box absolute position */ position: absolute; left: 50%; top: 50%; margin-top: -50px; margin-left: -50px; } </style> </head>Copy the code

Method 2: Use margin: Auto

<style>. Parent {/* parent box relative position */ position: relative; width: 300px; height: 300px; border: 1px solid #000; margin: 100px auto; } .child { width: 100px; height: 100px; border: 1px solid #999; background-color: skyblue; /* Box absolute position */ position: absolute; margin:auto; top: 0; bottom: 0; left: 0; right: 0; } </style>Copy the code

Method 3: Run display: table-cell

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
       display:inline-block;
    }
</style>
Copy the code

Method 4: Use Flex layout (common)

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        margin: 100px auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
    }
</style>
Copy the code

Method 5: Use Transform

<style> .parent { width: 300px; height: 300px; border: 1px solid #000; margin: 100px auto; /* Set relative position */ position: relative; } .child { width: 100px; height: 100px; border: 1px solid #999; background-color: skyblue; /* Box absolute position */ position: absolute; top: 50%; left:50%; transform: translate(-50%,-50%); } </style>Copy the code