div 水平垂直居中的方式

2023/1/22 css

# div 水平垂直居中的方式

<div class="wrapper">
  <div class="box"></div>
</div>
* {
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100vw;
  height: 100vh;
}

.box {
  width: 100px;
  height: 100px;
  background: red;
}

# flex

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

# grid

.wrapper {
  display: grid;
}
.box {
  align-self: center;
  justify-self: center;
}

# absolute + margin auto

.wrapper {
  position: relative;
}
.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

# absolute + transform

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

# table-cell

.wrapper {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.box {
  display: inline-block;
}

文字默认是水平显示,使用 writing-mode 可使文字垂直显示,writing-mode (opens new window)

    我记得
    赵雷