div垂直居中的方法

父元素:box1,子元素:box2;

持续补充中。。。。。

一、子div定宽高

1. flex布局

.box1{
  width: 300px;
  height: 300px;
  border: 1px solid red;
  display: flex;
  align-items: center;
}
.box2{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
}

2.  定位+上下左右为0

.box1{
  width: 300px;
  height: 300px;
  border: 1px solid red;
  position: relative;
}
.box2{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

3. 定位+平移translate

.box1{
  width: 300px;
  height: 300px;
  border: 1px solid red;
  position: relative;
}
.box2{
  width: 100px;
  height: 100px;
  border: 1px solid blue;
  position: absolute;
  top: 50%;
  transform: translate(0,-50%);
}

 

  

  

 

posted @ 2021-04-01 08:50  考拉很OK  阅读(46)  评论(0编辑  收藏  举报