当前位置: 首页 > 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 布局方法,它们更简洁、灵活且易于维护。

http://www.xdnf.cn/news/407251.html

相关文章:

  • 【启动盘制作】macbook 制作windows启动盘,重装 Windows 的详细教程
  • C++:公有,保护及私有继承
  • 数据结构-树(1)
  • 硬件设备基础
  • 豆瓣电影Top250数据工程实践:从爬虫到智能存储的技术演进(含完整代码)
  • Mysql使用PXC实现高可用
  • js 字符串中的特殊字符全部替换成定义对象里面key对应的value值(进阶篇)
  • Python60日基础学习打卡D12【虫豸版】
  • 如何使用 React Hooks 替代类组件的生命周期方法?
  • Linux服务器连接SSH工具FinalShell安装使用支持Linux文件上传下载
  • (自用)Java学习-5.8(总结,springboot)
  • 【合新通信】无人机天线拉远RFOF(射频光纤传输)解决方案
  • upload-labs通关笔记-第01关 文件上传之前端绕过(3种渗透方法)
  • 浙江大学 deepseek 公开课 第三季 第3期 - 陈喜群 教授 (附PPT下载) by 突破信息差
  • Linux笔记---信号(上)
  • SWMM在城市排水防涝规划中的实战应用:模型校准、情景模拟与工程决策
  • Linux进程10-有名管道概述、创建、读写操作、两个管道进程间通信、读写规律(只读、只写、读写区别)、设置阻塞/非阻塞
  • WordPress 网站上的 jpg、png 和 WebP 图片插件
  • 请解释 React Native 的新架构(Fabric 和 TurboModules)与旧架构的主要区别
  • 「光域」系列激光测距传感器:以光为尺,重构空间认知边界
  • 【华为HCIP | 华为数通工程师】821—多选解析—第二十二页
  • 详解 IRC协议 及客户端工具 WeeChat 的使用
  • OpenCV进阶操作:光流估计
  • Linux基础命令之目录管理——了解各种操作文件目录的命令,万字教学,超详细!!!(1)
  • OCCT知识笔记之分解BOX
  • 计算频谱的方法
  • 《基于 Kubernetes 的 WordPress 高可用部署实践:从 MariaDB 到 Nginx 反向代理》
  • 《AI大模型应知应会100篇》第59篇:Flowise:无代码搭建大模型应用
  • 免费批处理软件一键修改文件名称
  • 了解docker-compose.yml