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 布局方法,它们更简洁、灵活且易于维护。

相关推荐
rookie fish几秒前
Electron+Vite+Vue项目中,如何监听Electron的修改实现和Vue一样的热更新?[特殊字符]
前端·vue.js·electron
珹洺5 分钟前
Java-Spring入门指南(五)Spring自动装配
android·java·spring
她超甜i5 分钟前
前端通过后端给的webrtc的链接,在前端展示,并更新实时状态
前端·javascript·webrtc
歪歪10011 分钟前
Redux和MobX在React Native状态管理中的优缺点对比
前端·javascript·react native·react.js·架构·前端框架
Insist75311 分钟前
OpenEuler安装gitlab,部署gitlab-runner
linux·运维·服务器
帧栈11 分钟前
并发编程原理与实战(二十七)深入剖析synchronized底层基石ObjectMonitor与对象头Mark Word
java
东风西巷15 分钟前
Atlantis Word Processor:全方位的文字处理专家
前端·学习·word·软件需求
imHanweihu16 分钟前
基于POI-TL实现动态Word模板数据填充(含图表):从需求到落地的完整开发实践
java·onlyoffice·poi-tl
月夕·花晨19 分钟前
Gateway -网关
java·服务器·分布式·后端·spring cloud·微服务·gateway
失散1319 分钟前
分布式专题——6 Redis缓存设计与性能优化
java·redis·分布式·缓存·架构