css div垂直左右居中

65 阅读1分钟

方法1:

.parent{
  display: flex;
  align-items: center;
  justify-content: center;
}

方法2:

.parent{
  position: relative;
}

.child{
  position: absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
}

方法3:

.parent{
  position: relative;
}

.child{
  position: absolute;
  width: 100px;
  height: 100px;
  top:50%;
  left:50%;
  margin-left: -50px;
  margin-top: -50px;
}

方法4:

.parent{
  position: relative;        
}

.child{
  background-color: blue;       
  width: 100px;            
  height: 100px;              
  position: absolute;            
  top: 0;            
  bottom: 0;            
  left: 0;            
  right: 0;            
  margin: auto;       
}