css 水平垂直居中的五种方案

226 阅读1分钟

已知子元素宽高

方案一:父元素相对定位,子元素绝对定位,上下左右设为0,margin: auto;

.parent{  
  height: 100px;  
  width: 100px;  
  background-color: pink;  
  position: relative;
}
.son{  
  width: 30px;  
  height: 30px;  
  background-color: red;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

方案二:父元素相对定位,子元素绝对定位,left: 50%; top: 50%; margin-left:负子元素宽度的一半;margin-top: 负子元素高度的一半;

.parent{  
  height: 100px;  
  width: 100px;  
  background-color: pink;  
  position: relative;
}
.son{
  width: 30px;
  height: 30px;
  background-color: red;
  position: absolute;
  left: 50%; 
  top: 50%;
  margin-left: -15px;
  margin-top: -15px;
}

未知子元素宽高

方案一:给父元素设置display: flex; align-items: center; justify-content: center;

.parent{
  height: 100px;
  width: 100px;
  background-color: pink;
  display: flex;
  align-items: center;
  justify-content: center;
}
.son{
  background-color: red;
}

方案二:父元素相对定位,子元素决定定位,left: 50%; top: 50%; transform: translate(-50%, -50%);

.parent{
  height: 100px;
  width: 100px;
  background-color: pink;
  position: relative;
}
.son{
  background-color: red;
  position: absolute;
  left: 50%; 
  top: 50%;
  transform: translate(-50%, -50%);
}

方案三:父元素display: table-cell; text-align: center; vertical-align: middle; 子元素display: inline-block;

.parent{
  height: 100px;
  width: 100px;
  background-color: pink;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.son{
  background-color: red;
  display: inline-block;
}