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

css水平垂直居中的几种方法

作者:疾风雨辰   发布日期:2026-03-06   浏览:61

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

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

/* 方法3:使用绝对定位和 transform */
.container {
  position: relative;
  height: 100vh;           /* 设置容器高度为视口高度 */
}

.item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 移动到中心位置 */
}

/* 方法4:使用表格布局 */
.container {
  display: table;
  height: 100vh;           /* 设置容器高度为视口高度 */
  width: 100%;             /* 设置容器宽度为100% */
}

.item {
  display: table-cell;
  text-align: center;      /* 水平居中 */
  vertical-align: middle;  /* 垂直居中 */
}

解释说明:

  1. Flexbox

    • display: flex 将容器设置为弹性盒子。
    • justify-content: centeralign-items: center 分别用于水平和垂直居中。
    • height: 100vh 确保容器高度为整个视口高度。
  2. Grid

    • display: grid 将容器设置为网格布局。
    • place-items: centerjustify-itemsalign-items 的简写,用于同时水平和垂直居中。
    • height: 100vh 确保容器高度为整个视口高度。
  3. 绝对定位和 transform

    • .container 设置为相对定位。
    • .item 设置为绝对定位,并通过 top: 50%left: 50% 将元素移动到容器的中心位置。
    • transform: translate(-50%, -50%) 将元素本身向左和向上移动自身宽高的一半,从而实现精确居中。
  4. 表格布局

    • .container 设置为表格显示模式。
    • .item 设置为表格单元格,并通过 text-align: centervertical-align: middle 实现水平和垂直居中。

上一篇:css样式优先级

下一篇:css 文字倾斜

大家都在看

css好看的字体

css 红色

css 瀑布流布局grid

css盒子

css三种引入方式

换行 css

css文字超长省略号

css图片铺满整个背景

css背景图铺满

css 渐变字体

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

Laravel 中文站