实现垂直水平居中的九种方式

123 阅读1分钟
<div class="box">
  <p>hello</p>
</div>
  1. grid布局
1.1
.box{
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: grid;
  align-items: center;/* 单元格内容垂直居中 */
  justify-items: center;/* 单元格内容垂直居中 */
}
p{
  background: red;
}

1.2
.box{
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: grid;
  align-items: center;/* 单元格内容垂直居中 */
  justify-content: center;/* 整个内容区域在容器里水平居中 */
}
p{
  background: red;
}

1.3
.box{
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: grid;
}
p{
  background: red;
  margin: auto;
}

2.flex布局

2.1
.box{
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: flex;
  align-items: center;/* 交叉轴方向上中点对齐 */
  justify-content: center;/* 主轴方向上居中 */
}
p{
  background: red;
}

2.2
.box{
  height: 200px;
  width: 200px;
  border: 1px solid;
  display: flex;
}
p{
  background: red;
  margin: auto;
}

3.table-cell

<div class="wrapper">
  <div class="box">
    <p>hello</p>
  </div>
</div>

CSS:
.wrapper{
  display: table;
  width: 100%;
}
.box{
  height: 200px;
  border: 1px solid;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
p{
  background: red;
  display: inline-block;
}

4.绝对定位

.box{
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: relative;
}
p{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}

5.伪元素

.box{
  width: 200px;
  height: 200px;
  border: 1px solid;
  text-align: center;
}
.box::after{
  content: '';
  line-height: 200px;
}
p{
  display: inline-block;
}
.box{
  width: 200px;
  height: 200px;
  border: 1px solid;
  position: relative;
}
p{
  width: 100px;
  height: 40px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}