令某元素完全居中的方案

发现面试官考css部分知识的时候,挺喜欢拿这个作为例子,于是整理后记录下来。

思考:

需要实现这种需求的时候,一般会有两种情况:

1.知道该元素宽高

2.不知道该元素宽高

对第一种情况

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

第二种情况有多种方案:

.item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform(-50%, -50%);
}
.item {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
<!-- box为父元素,推荐此方案 -->
.box {
  display: table-cell;
  vertical-align: middle;
}
.item {
  margin: 0 auto;
}
.box {
  display: flex;
  justify-content: center;
  align-items: center;
}
.item {

}
.box {
  text-align: center;
}
.item {
  display: inline-block;
  vertical-align: middle;
}
<!-- foolitem为兄弟元素 -->
.fool {
  width: 0;
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}