This is an explanation of the video content.
 Everything to games
Spanning time and space ...
21

 |   | 

CSS文本和div垂直居中方法

实现文本和 div 元素的垂直居中有以下几种常用方法:

  • line-height 属性
  • display: table-cell 和 vertical-align: middle
  • position 和 transform
  • Flexbox 布局
  • Grid 布局

1.使用 line-height 属性

.container {
  height: 50px; /* 设置容器高度 */
  line-height: 50px; /* 设置行高等于容器高度 */
}

.text {
  display: inline-block;
  vertical-align: middle;
}

这种方法适用于单行文本。将行高设置为容器高度,并将文本元素设置为 inline-block 并垂直居中。

2.使用 display: table-cell 和 vertical-align: middle

.container {
  display: table-cell;
  vertical-align: middle;
  height: 50px; /* 设置容器高度 */
}

.text {
  display: inline-block;
}

这种方法可以用于多行文本。将容器设置为 table-cell 并设置 vertical-align: middle,文本元素设置为 inline-block。

3.使用 position 和 transform

.container {
  position: relative;
  height: 50px; /* 设置容器高度 */
}

.text {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

这种方法通过绝对定位和 transform 属性来实现垂直居中。容器设置 position: relative,文本元素设置 position: absolute 并通过 transform: translateY(-50%) 将其上移自身高度的一半。

4.使用 Flexbox 布局

.container {
  display: flex;
  align-items: center;
  height: 50px; /* 设置容器高度 */
}

.text {
  /* 无需额外样式 */
}

Flexbox 布局提供了 align-items: center 属性,可以轻松实现垂直居中。容器设置 display: flex 并设置 align-items: center,文本元素就会自动垂直居中。

5.使用 Grid 布局

.container {
  display: grid;
  align-items: center;
  height: 50px; /* 设置容器高度 */
}

.text {
  /* 无需额外样式 */
}

Grid 布局也提供了 align-items: center 属性来实现垂直居中。容器设置 display: grid 并设置 align-items: center,文本元素就会自动垂直居中。

这些都是常见的实现文本和 div 元素垂直居中的 CSS 方法,您可以根据具体需求选择合适的方式。

21 🌐Frontend ↦ CSS开发技巧 __ 193 字
 CSS开发技巧 #3