盒子的几种水平垂直居中方法总结

321 阅读1分钟

盒子水平垂直居中的几种方式

<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>

一 使用flex布局

<style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* flex布局 */
        .box1 {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 600px;
            height: 600px;
            background-color: aquamarine
        }

        .box2 {
            width: 200px;
            height: 200px;
            background-color: brown;
        }
    </style>

二 使用位移和定位

<style>
  .box1 {
            position: relative;
            width: 600px;
            height: 600px;
            background-color: aquamarine
        }

        .box2 {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 200px;
            height: 200px;
            background-color: brown;
        }
    </style>

三 使用定位和margin

<style>
     .box1 {
             position: relative;
             width: 600px;
             height: 600px;
             background-color: aquamarine
           }

    .box2 {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
            width: 200px;
            height: 200px;
            background-color: brown;
        }
    </style>