css child element div (known width and height, unknown width and height) vertically center the parent element div

css child element div (known width and height, unknown width and height) vertically center the parent element div

1. Known child element div width and height

1. Son-in-parent phase (absolute positioning of child elements, relative positioning of parent elements)

2、left:50%    top:50%

3. Margin-left: half of its own width margin-top: half of its own height

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>子div水平垂直居中</title>
    <style>
        .outer {
            width: 200px;
            height: 200px;
            background: pink;
            position: relative;
        }

        .inner {
            width: 50px;
            height: 50px;
            background: green;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -25px;
            margin-top: -25px;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner">
            子
        </div>
    </div>
</body>
</html>

Two, unknown child element div width and height

The son is not the father, and then use the transform property in css3 to set the value of translate to center

        .inner {
            background: green;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
            -webkit-transform: translateX(-50%) translateY(-50%);
        }

Third, use display: flex to realize the subdiv size is not fixed and vertically centered

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>子div水平垂直居中</title>
    <style>
        .outer {
            width: 200px;
            height: 200px;
            background: pink;
            display: flex;
            justify-content: center;/*实现水平居中*/
            align-items:center; /*实现垂直居中*/
        }

        .inner {
            width: 50px;
            height: 50px;
            background: green;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner">
            子
        </div>
    </div>
</body>
</html>

 

 css text is centered horizontally and vertically (the parent element div has known width and height and unknown width and height):  https://blog.csdn.net/qq_40015157/article/details/113844403

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113845120