css不确定宽高的盒子垂直居和水平居中

1.flex布局 justify-content: center;(水平居中)  align-items: center;(垂直居中)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            .box{
                height: 100vh;
                width: 50%;
                background: #f3f300;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .box01{
                height: 300px;        /* 这里可以改变 */
                width: 300px;        /* 这里可以改变 */
                background-color: #6676FF;
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div class="box01"></div>
        </div>
    </body>
</html>

 2.display:table-cell 表格

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            .box{
                height: 100vh;
                width: 50%;
                background: #f3f300;
                display: table-cell;
                vertical-align: middle;
            }
            .box01{
                height: 300px;        /* 这里可以改变 */
                width: 300px;        /* 这里可以改变 */
                background-color: #6676FF;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div class="box01"></div>
        </div>
    </body>
</html>

3.position定位 + transform过渡

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            .box{
                height: 100vh;
                width: 50%;
                background: #f3f300;
                position: relative;
            }
            .box01{
                height: 300px;        /* 这里可以改变 */
                width: 300px;        /* 这里可以改变 */
                background-color: #6676FF;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%,-50%);
            }
        </style>
    </head>
    <body>
        <div class="box">
            <div class="box01"></div>
        </div>
    </body>
</html>

 

posted @ 2020-07-01 09:07  我也不想那么菜  阅读(468)  评论(0编辑  收藏  举报