Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

css垂直居中的几种方法

作者:余烬已熄   发布日期:2026-04-21   浏览:112

/* 方法1: 使用 Flexbox */
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 300px;           /* 设置容器高度 */
}

/* 方法2: 使用 Grid */
.container {
  display: grid;
  place-items: center;     /* 同时水平和垂直居中 */
  height: 300px;           /* 设置容器高度 */
}

/* 方法3: 使用绝对定位 + transform */
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 调整元素自身位置 */
}

/* 方法4: 使用 table-cell */
.container {
  display: table;
  height: 300px;           /* 设置容器高度 */
  width: 100%;             /* 设置容器宽度 */
}
.centered {
  display: table-cell;
  vertical-align: middle;  /* 垂直居中 */
  text-align: center;      /* 水平居中 */
}

/* 方法5: 使用 line-height (仅适用于单行文本) */
.container {
  height: 300px;           /* 设置容器高度 */
  line-height: 300px;      /* 行高与容器高度相同 */
  text-align: center;      /* 水平居中 */
}

解释说明:

  1. Flexbox:通过 display: flexalign-items: center 可以轻松实现垂直居中,同时配合 justify-content: center 实现水平居中。
  2. Grid:使用 display: gridplace-items: center 可以一次性实现水平和垂直居中。
  3. 绝对定位 + transform:通过 position: absolute 将元素放置在容器的中心,再用 transform: translate(-50%, -50%) 调整元素自身的位置。
  4. table-cell:将容器设置为 display: table,子元素设置为 display: table-cell,并使用 vertical-align: middle 实现垂直居中。
  5. line-height:对于单行文本,可以将 line-height 设置为与容器高度相同,从而实现垂直居中。

上一篇:css 设置字体

下一篇:css ::before

大家都在看

css好看的字体

css 红色

css 瀑布流布局grid

css盒子

css字体加粗怎么设置的

css三种引入方式

换行 css

css文字超长省略号

css图片铺满整个背景

css背景图铺满

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站