CSS居中

43 阅读1分钟

文字水平垂直居中

设置文字垂直居中,需要将line-height设置为父容器的高度,水平居中则需要设置text-align为center。

.center {
      height: 80px;
      line-height: 80px;
      text-align: center;
      background-color: red;
 }
<div class="center">Test</div>

块级元素水平垂直居中

下面给出html结构

<div class="father">
    <div class="son"></div>
  </div>

image.png

1. 定位+margin(定宽)

.father {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px solid red;
}
.son {
  width: 80px;
  height: 80px;
  background-color: blue;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}
 

2. 定位+transform(定宽)

.father {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px solid red;
}

.son {
  width: 80px;
  height: 80px;
  background-color: blue;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}

3. flex布局

.father {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
}

.son {
  width: 80px;
  height: 80px;
  background-color: blue;
}

4. grid布局

.father {
  width: 200px;
  height: 200px;
  display: grid;
  justify-content: center;
  align-items: center;
  border: 1px solid red;
}

.son {
  width: 80px;
  height: 80px;
  background-color: blue;
}

5. table布局

.father {
  width: 200px;
  height: 200px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  border: 1px solid red;
}

.son {
  width: 80px;
  height: 80px;
  background-color: blue;
  display: inline-block;
}