块元素水平垂直居中

通过定位的方式可使块元素在其父元素内垂直水平居中,前提条件是,父元素的position不是static
备注:块元素脱离文档流后,可见区域宽度和高度由内容区内容、内边距、边框撑开

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="css/reset.css" />
        <style type="text/css">
            .box1{
                height: 100px;
                background-color: skyblue;
            }
            .box2{
                box-sizing: border-box;
                width: 400px;
                height: 500px;
                margin: 20px auto;
                border: 5px solid #333;
                position: relative;
            }
            .box2 h1{
                background-color: #e2e2e2;
                text-align: center;
                height: 25px;
                font: 400 20px/25px sans-serif;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%,-50%);
            }
        </style>
    </head>
    <body>
        <div class="box1"></div>
        <div class="box2">
            <h1>AAA</h1>
        </div>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/cccmercy/article/details/81144260