元素水平垂直居中方法

615 阅读1分钟

元素水平垂直居中方法

1.绝地定位 + margin: auto

<style>
        .box1 {
           width: 500px;
           height: 500px;
           background-color:aqua;
           position: relative;
        }
        .box2 {
            width: 100px;
            height: 100px;
            background-color: blanchedalmond;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
    </style>
</head>
<body>
   <div class="box1">
       <div class="box2"></div>
   </div>
</body>

2. 绝对定位 + margin 负值

 <style>
        .box1 {
           width: 500px;
           height: 500px;
           background-color:aqua;
           position: relative;
        }
        .box2 {
            width: 100px;
            height: 100px;
            background-color: blanchedalmond;
            position: absolute;
           top: 50%;
           left: 50%;
           margin-left: -50px; // width 的一半
           margin-top: -50px; // height 的一半
        }
    </style>
</head>
<body>
   <div class="box1">
       <div class="box2"></div>
   </div>
</body>

3.绝对定位 + transform

 <style>
        .box1 {
           width: 500px;
           height: 500px;
           background-color:aqua;
           position: relative;
        }
        .box2 {
            width: 100px;
            height: 100px;
            background-color: blanchedalmond;
            position: absolute;
           top: 50%;
           left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
   <div class="box1">
       <div class="box2"></div>
   </div>
</body>

4.flex 布局

将父元素设置为 display: flex , justify-content: center 主轴居中,align-items: center; 交叉轴居中

 <style>
        .box1 {
           width: 500px;
           height: 500px;
           background-color:aqua;
           display: flex;
           justify-content: center;
           align-items: center;
        }
        .box2 {
            width: 100px;
            height: 100px;
            background-color: blanchedalmond;
        }
    </style>
</head>
<body>
   <div class="box1">
       <div class="box2"></div>
   </div>
</body>

5. table-cell(未脱离文档流的)

设置父元素的display:table-cell,并且vertical-align:middle,这样子元素可以实现垂直居中。

<style>
        .box1 {
           width: 500px;
           height: 500px;
           background-color:aqua;
           display: table-cell;
           vertical-align: middle;
        }
        .box2 {
            width: 100px;
            height: 100px;
            background-color: blanchedalmond;
            margin: 0 auto;
        }
    </style>
</head>
<body>
   <div class="box1">
       <div class="box2"></div>
   </div>
</body>