垂直居中

114 阅读1分钟

视频地址(技术蛋)

<div class="app">
    <p>AFASDASDFASFDASFASDFAD</p>
</div>
.app {
  height: 100px;
  background-color: skyblue;
}

方案一: 子元素的line-height等于父元素的height

  • 优点: 简单
  • 缺点: 不适用于多行文字
.app > p {
  line-height: 100px;
}

方案二: flex

  • 优点: 简单
  • 缺点: 无法兼容老版浏览器
.app {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

方案三: grid

  • 优点: 布局很牛
  • 缺点: 无法兼容老版浏览器, 上手难度高
.app {
  display: grid;
  grid-auto-columns: 1fr;
  justify-content: center;
  align-items: center;
}

方案四: position

  • 优点: 简单
  • 缺点: 脱离文档流
.app {
  position: relative;
}
.app > p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

方案五: vertical-align: middle

  • 优点: 兼容性好
  • 缺点: 复杂
.app > p {
  display: inline-block;
  vertical-align: middle;
}
.app::after {
  content: "";
  display: inline-block;
  height: 100%;
  width: 0;
  vertical-align: middle;
}

方案六: flex + margin

.item {
  width: 50px;
  height: 50px;
  background-color: deeppink;
  border: 1px solid #fff;
}
.part {
  padding: 10px;
  background: #000;
  margin-bottom: 30px;
  display: flex;  /* 必加<------------------- */ 
}

.part1 {
  height: 100px;
}
.part1 .item {
  margin: auto;
}

.part5 {
  flex-wrap: wrap;
}
.part5 .item {
  --n: 7;
  --space: calc(100% - var(--n) * 52px);
  --m: calc(var(--space) / var(--n) / 2);
  margin: 10px var(--m);
}