HTML5 中实现盒子水平垂直居中的方法

在 HTML5 中,有几种方法可以让一个定位的盒子在父容器中水平垂直居中。以下是几种常用的方法:

使用 Flexbox 布局

html 复制代码
<div class="parent">
  <div class="child">居中内容</div>
</div>

<style>
  .parent {
    display: flex;
    justify-content: center;  /* 水平居中 */
    align-items: center;      /* 垂直居中 */
    height: 100vh;            /* 设置父容器高度 */
  }
  
  .child {
    /* 子元素不需要特殊样式 */
  }
</style>

使用 Grid 布局

html 复制代码
<div class="parent">
  <div class="child">居中内容</div>
</div>

<style>
  .parent {
    display: grid;
    place-items: center;  /* 水平和垂直居中 */
    height: 100vh;
  }
</style>

使用绝对定位 + transform

html 复制代码
<div class="parent">
  <div class="child">居中内容</div>
</div>

<style>
  .parent {
    position: relative;
    height: 100vh;
  }
  
  .child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>

使用绝对定位 + margin auto

html 复制代码
<div class="parent">
  <div class="child">居中内容</div>
</div>

<style>
  .parent {
    position: relative;
    height: 100vh;
  }
  
  .child {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: fit-content;  /* 或者指定宽度 */
    height: fit-content; /* 或者指定高度 */
  }
</style>

使用表格布局(传统方法)

html 复制代码
<div class="parent">
  <div class="child">居中内容</div>
</div>

<style>
  .parent {
    display: table;
    width: 100%;
    height: 100vh;
  }
  
  .child {
    display: table-cell;
    text-align: center;  /* 水平居中 */
    vertical-align: middle;  /* 垂直居中 */
  }
</style>

现代 Web 开发中,推荐优先使用 Flexbox 或 Grid 布局方法,它们更简洁、灵活且易于维护。

相关推荐
guo_wen_qiang几秒前
springboot如何自定义一个启动器starter
java·spring boot·intellij-idea
许彰午4 分钟前
55-字典缓存与通知SPI
java·低代码·架构
captain3769 分钟前
HTTP(2)
java·网络·http·java-ee
徐子童11 分钟前
介绍MVCC机制
java·mysql·面试题·秋招·并发·mvcc
Wang's Blog12 分钟前
Java 项目实战: 外卖平台-启用禁用员工账号与Long精度丢失修复
java·服务器
乌暮17 分钟前
Java 抽象类与接口详解:半成品图纸 vs 能力合同
java·开发语言·后端·学习
一条泥憨鱼24 分钟前
苍穹外卖【day12| 工作台,通过Apache POI导入/导出运营数据】
java·后端·苍穹外卖
心平气和量大福大29 分钟前
android-权限
android·java
IT_陈寒30 分钟前
Redis大key删除引发的服务雪崩,这次我真记住了
前端·人工智能·后端
006_35 分钟前
ruoyi-vue-plus项目 minio外网访问配置
java