子元素上下左右居中的方法

<div class="father">

<div class="child">

</div>

</div>

child分很多种情况

  • 行内元素:text-align + line-height
.father{
  width:300px;
   height:300px;
   text-align:center;
   line-height:300px;
} 

定宽定高:absolute + margin

.father{
  position: relative;
}
.child{
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -150px 0 0 -150px;
}
/* 或者 */
.child{
  position: absolute;
  left: 0;
  top: 0; 
  right: 0; 
  bottom: 0;
  margin: auto;
}

 

不定高:absolute + translate

  • .father{
      position: relative;
    }
    .child{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
    
  • 不定高:flex
  • .father{
      display: flex; 
    }
    .child{
      margin:auto;
    }
    /* 或者 */
    .child{
      justify-content: center;
      align-items: center;
    }
    
  • table方式:
  • .father{
      display: table; 
    }
    .child{
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    
posted @ 2019-03-25 18:21  yanruw  阅读(708)  评论(0编辑  收藏  举报