五种方法实现div的水平垂直居中

430 阅读1分钟

原创不易,求一键三连!!!

1.运用absolute和calc垂直居中

    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .demo{
            width: 300px;
            height: 300px;
            background-color: red;
            position: absolute;
            top: calc(50% - 150px);
            left: calc(50% - 150px);
        }
    </style>
    <body>
        <div class="demo"></div>
    </body>

2.运用flex布局进行垂直居中

    <style>
        *{
            padding: 0;
            margin: 0;
        }
        body{
            //必须标明父盒子的具体高度,有局限性
            height: 600px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .demo{
            width: 300px;
            height: 300px;
            background-color: red;
        }
    </style>
    <body>
        <div class="demo"></div>
    </body>

3.运用absolute进行垂直居中

    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .demo{
            width: 300px;
            height: 300px;
            background-color: red;
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -150px 0 0 -150px;
        }
    </style>
    <body>
        <div class="demo"></div>
    </body>

4.运用margin:auto进行垂直居中

    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .demo{
            width: 300px;
            height: 300px;
            background-color: red;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
    </style>
    <body>
        <div class="demo"></div>
    </body>

5.运用transform+absolute实现的居中

    <style>
      * {
        padding: 0;
        margin: 0;
      }
      .demo {
        width: 300px;
        height: 300px;
        background-color: red;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translateX(-50%) translateY(-50%);
      }
    </style>
    <body>
        <div class="demo"></div>
    </body>

统一效果图如下:

image.png