CSS:实现垂直居中的居中方案

55 阅读1分钟

flex

html

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

css

  .parent{
         border: 1px solid red;
         height: 500px;
         width: 500px;
         display: flex;
         justify-content: center;
         align-items: center;
     }
 ​
     .child{
         border:1px solid red;
     }

absolute+margin:auto

html

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

css

     .parent{
         border: 1px solid red;
         height: 500px;
         width: 500px;
         position: relative;
     }
 ​
     .child{
         border:1px solid red;
         position: absolute;
         height: 100px;
         width: 100px;
         top: 0;
         left: 0;
         right: 0;
         bottom: 0;
         margin: auto;
     }

transform: translate(-50%,-50%)

html

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

css

     .parent{
         border: 1px solid red;
         height: 500px;
         width: 500px;
         position: relative;
     }
 ​
     .child{
         border:1px solid red;
         position: absolute;
         top:50%;
         left: 50%;
         transform: translate(-50%,-50%) ;
     }

margin-top:-50%

html

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

css

     .parent{
         border: 1px solid red;
         height: 500px;
         width: 500px;
         position: relative;
     }
 ​
     .child{
         border:1px solid red;
         position: absolute; 
         width: 100px;
         height: 100px;
         top:50%;
         left: 50%;
         margin-left: -50px;
         margin-top: -50px;
     }

table

table表格会自动垂直居中

html

     <table class="parent">
         <tr>
             <td class="child">
                 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
             </td>
         </tr>
     </table>

css

     .parent {
         border: 1px solid red;
         height: 500px;
 ​
     }
 ​
     .child {
         border: 1px solid red;
 ​
     }

div伪装成table

html

     <div class="table">
         <div class="td">
             <div class="child">
                 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈
             </div>
         </div>
     </div>

css

    .table{
     display: table;
     border: 1px solid red;
     height: 500px;
    }
    .td{
     border: 1px solid red;
     display: table-cell;
     vertical-align: middle;
    }