css使盒子水平垂直居中的常见方法

1,695 阅读1分钟

css实现盒子的垂直居中显示

Snipaste_2022-04-03_19-34-04.png

body内容区

<body>
<div class="parent">
    <div class="child"></div>
</div>
</body>

方法一:利用定位(常用)

<style>
        .parent {
            /*父盒子相对定位 */
            position: relative;
            width: 300px;
            height: 300px;
            border: 1px solid #000;
            margin: 100px auto;
        }
        .child {
            width: 100px;
            height: 100px;
            border: 1px solid #999;
            background-color: skyblue;
            /*子盒子绝对定位 */
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -50px;
            margin-left: -50px;
        }
    </style>
</head>

方法二:利用margin:auto

<style>
    .parent {
        /*父盒子相对定位 */
        position: relative;
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        margin: 100px auto;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
        /*子盒子绝对定位 */
        position: absolute;
        margin:auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }
</style>

方法三:利用display:table-cell

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
       display:inline-block;
    }
</style>

方法四:利用flex布局(常用)

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        margin: 100px auto;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
    }
</style>

方法五:利用transform

<style>
    .parent {
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        margin: 100px auto;
        /*设置相对定位*/
        position: relative;
    }
    .child {
        width: 100px;
        height: 100px;
        border: 1px solid #999;
        background-color: skyblue;
        /*子盒子绝对定位*/
        position: absolute;
        top: 50%;
        left:50%;
        transform: translate(-50%,-50%);
    }
</style>