CSS之垂直居中的方法

75 阅读1分钟

说明:垂直居中是布局中最常见的效果之一,方法也有很多。

<div class="container">
    <div class="content">垂直居中<div>
</div>

2.png

  1. display:table-cell和vertical-align:middle样式实现
    .container {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        border: 1px solid black;
    }
  1. flex布局实现
     .container {
        width: 200px;
        height: 200px;
        display: flex;
        justify-content:center;
        align-items:Center;
        background-color: skyblue;
    }
  1. margin:auto和绝对定位实现
    .container {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: skyblue;
    }
    
    .content {
        width: 50%;  
        height: 50%;  
        background: pink;
        overflow: auto;  
        margin: auto;  
        position: absolute;  
        top: 0; 
        left: 0; 
        bottom: 0; 
        right: 0;  
   }
  1. 绝对定位和负边距实现
     .container {
        position: relative;
        width: 200px;
        height: 200px;
        background-color: skyblue;
      }
      
    .content {
        width: 100px;  
        height: 100px;  
        background: pink;
        position: absolute;
        top:50%;
        left:50%;
        margin-left:-50px;
        margin-top:-50px;
    }
  1. 第5种方法是第四种方法的变形,将 margin-top 和 margin-left 负值替换成,transform:translateX(-50%)和 transform:translateY(-50%)即可。