天天看點

實作元素垂直居中的幾種方法

一、flex彈性布局方式 實作居中

HTML結構

<div class="wrap">
    <div class="content"></div>
  </div>
           

CSS樣式一

<style>
    .wrap{
      width: 400px;
      height: 400px;
      background-color: beige;
      /* 實作垂直居中-flex */
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .content{
      width: 100px;
      height: 100px;
      background-color: chartreuse;
    }
  </style>
           

二、translate與定位配個居中

CSS樣式二

.wrap{
      width: 400px;
      height: 400px;
      background-color: beige;
      /* translate要與定位配合使用 */
      position: relative;
    }
    .content{
      width: 100px;
      height: 100px;
      background-color: chartreuse;
      position: absolute;
      top: 50%;
      left: 50%;
      /* 使用translate 方法*/
      transform: translate(-50%,-50%);
    }
           

三、将父元素轉換為表格,使用vertical-align: middle實作垂直居中

CSS樣式三

<style>
    .wrap{
      width: 400px;
      height: 400px;
      background-color: beige;
      /* 實作垂直居中 */
      display: table-cell;
      vertical-align: middle;
    }
    .content{
      width: 100px;
      height: 100px;
      background-color: chartreuse;
      /* 實作水準居中 */
      margin: 0 auto;
    }
  </style>
           

四、“子絕父相”

CSS樣式四

<style>
    /* 使用子絕父相定位居中 */
    .wrap{
      width: 400px;
      height: 400px;
      background: yellow;
      /* 父元素絕相對定位 */
      position: relative;
    }
    .content{
      width: 100px;
      height: 100px;
      background: yellowgreen;
      /* 子元素絕對定位 ,并使用margin:auto水準居中*/
      margin: auto;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
  </style>
           

效果展示:

實作元素垂直居中的幾種方法

繼續閱讀