当前位置: 首页 > news >正文

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

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

使用 Flexbox 布局

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

使用 Grid 布局

<div class="parent"><div class="child">居中内容</div>
</div><style>.parent {display: grid;place-items: center;  /* 水平和垂直居中 */height: 100vh;}
</style>

使用绝对定位 + transform

<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

<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>

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

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

相关文章:

  • C++ 跨平台开发挑战与深度解决方案:从架构设计到实战优化
  • 安装hadoop
  • Modbus协议介绍
  • mac M2能安装的虚拟机和linux系统系统
  • 【时时三省】(C语言基础)字符数组的输入输出
  • 【C++进阶篇】多态
  • 使用Docker安装Dify
  • winreg查询Windows注册表的一些基本用法
  • 【Linux网络】————HTTP协议详解
  • 运算放大器相关的电路
  • Maven 项目中将本地依赖库打包到最终的 JAR 中
  • 【AI】mcp server是什么玩意儿
  • Python, FastAPI 与 RESTful API:构建高效 Web 服务的指南
  • SQLite 数据库常见问题及解决方法
  • 小结: Port Security,DHCP Snooping,IPSG,DAI,
  • 《汽车软件升级通用技术要求》 GB 44496-2024——解读
  • RN 鸿蒙混合开发实践(踩坑)
  • 每日Prompt:超现实交互场景
  • 动态网站 LNMP
  • 基于LNMP架构的个人博客系统部署
  • 外企聊营商|波音速度:创新审批促“起飞”
  • 沈阳一超市疑借领养名义烹食流浪狗,当地市监局:已收到多起投诉
  • 生态环境保护督察工作条例对督察对象和内容作了哪些规定?有关负责人答问
  • 中共中央、国务院印发《生态环境保护督察工作条例》
  • 长沙通报一出租房疑存非法代孕:查封涉事场所,相关人员被控制
  • 百利天恒董事长向复旦捐赠三千万元,用于支持创新药物靶点发现等师资建设需要