Margin can only center block-level elements horizontally, and positioning is needed for vertical centering

First of all, we have to understand what auto means. Auto automatically fills the remaining space.

Block-level element, even if we set the width, it still occupies a line by itself. In the css specification, the element's left outer margin + left border width + left inner margin + content width + right inner margin + right border + Right margin = the width of the containing block. If we set his left and right margins to auto, he will achieve the remaining distance equally, thus achieving a horizontal centering effect.

However, the height of the block-level element does not automatically expand, so its external size is not automatically filled with the parent element, and there is no remaining space. Therefore, setting auto up and down the margin cannot achieve vertical centering.

But we can achieve it through positioning + margin;

But if the parent element is the body, this method is not feasible.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 500px;
            height: 500px;
            position: relative;
            background-color: pink;
        }
        .box div {
            width: 200px;
            height: 200px;
            background-color: skyblue;
            
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
    </style>
</head>
<body>
    <div class="box">
         <div></div>
    </div>
   
</body>
</html>

 

Guess you like

Origin blog.csdn.net/xingxinglinxi/article/details/108606684