CSS 子元素在父元素中垂直居中

父元素设置为相对布局,子元素设置为绝对布局,并且设置上下左右边距都为0,设置子元素的宽度为500px,这样就是子元素占据了整个容器,此时margin设置为auto才起作用,具体代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        .father {
            height: 200px;
            position: relative;
            background-color: red;
        }
        .son {
            background-color: cadetblue;
            position: absolute;
            top: 0px;
            bottom: 0px;
            left: 0px;
            right: 0px;
            width:500px;
            height: 90px;
            margin: auto;
        }

    </style>
</head>
<body>

<div class="father">
    123
    <div class="son">456</div>
</div>

</body>
</html>

效果图:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/u010545480/article/details/79178941