CSS 垂直居中体现的方法

[复制链接]
发表于 2026-2-8 17:37:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1. Flexbox

使用 Flexbox 是一种非常常见且机动的方法,可以轻松实现水平和垂直居中。
  1. css复制代码
  2. .container {
  3.   display: flex;
  4.   justify-content: center; /* 水平居中 */
  5.   align-items: center;      /* 垂直居中 */
  6.   height: 100vh;            /* 使容器高度为视口高度 */
  7. }
复制代码
2. Grid

使用 CSS Grid 也可以实现垂直居中。
  1. css复制代码
  2. .container {
  3.   display: grid;
  4.   place-items: center; /* 水平和垂直居中 */
  5.   height: 100vh;
  6. }
复制代码
3. 使用 position 和 transform

这种方法实用于具有固定宽度和高度的元素。
  1. css复制代码
  2. .container {
  3.   position: relative;
  4.   height: 100vh;
  5. }
  6. ​
  7. .element {
  8.   position: absolute;
  9.   top: 50%;
  10.   left: 50%;
  11.   transform: translate(-50%, -50%);
  12. }
复制代码
4. 使用 line-height

这种方法实用于单行文本或具有固定高度的块元素。
  1. css复制代码
  2. .container {
  3.   height: 100px; /* 设定固定高度 */
  4.   line-height: 100px; /* 与容器高度相同 */
  5.   text-align: center; /* 水平居中 */
  6. }
复制代码
5. 使用 table-cell

使用 display: table-cell; 可以在倒霉用表格的环境下实现垂直居中。
  1. css复制代码
  2. .container {
  3.   display: table;
  4.   height: 100vh;
  5.   width: 100%;
  6. }
  7. ​
  8. .element {
  9.   display: table-cell;
  10.   vertical-align: middle; /* 垂直居中 */
  11.   text-align: center; /* 水平居中 */
  12. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表