CSS居中对齐 (水平垂直居中对齐)

方案一:flex布局【推荐】

给容器添加样式

复制代码
display: flex;
justify-content: center;
align-items: center;
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid gray;
        width: 200px;
        height: 100px;

      }

      .item {
        width: 50px;
        height: 50px;
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <span class="item">水平垂直居中</span>
    </div>
  </body>
</html>

方案二:子绝父相 + transform (CSS3)

限制条件:浏览器需支持CSS3,比较老的浏览器不适用

给容器(父元素)添加样式

html 复制代码
position: relative

给内部元素添加样式

html 复制代码
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

方案三:子绝父相 + 自动外边距(指定高度和宽度)

给容器(父元素)添加样式

复制代码
position: relative

给内部元素添加样式

复制代码
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;

方案四:子绝父相 + 负外边距 (知道宽度和高度 + 宽度和高度计算)不推荐

限制条件 :需知道内部元素的宽度和高度

给容器(父元素)添加样式

复制代码
position: relative

给内部元素添加样式

复制代码
position: absolute;
left:50%;
margin-left:-内部元素宽度的一半;
top: 50%;
margin-top: -内部元素高度的一半;
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        margin: 30px 30px 0px 300px;
        border: 1px solid gray;
        height: 100px;
        position: relative;
      }
      .item {
        background-color: yellow;
        position: absolute;
        left: 50%;
        margin-left: -150px;
        top: 50%;
        margin-top: -25px;
        width: 300px;
        height: 50px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <span class="item">水平垂直居中 -- 子绝父相 + 负外边距</span>
    </div>
  </body>
</html>
相关推荐
雪碧聊技术13 分钟前
前端项目代码发生改变,如何重新部署到linux服务器?
前端·vue3·centos7·代码更新,重新部署
liulilittle36 分钟前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
wordbaby1 小时前
Expo 进阶指南:赋予 TanStack Query “原生感知力” —— 深度解析 AppState 与 NetInfo
前端·react native
Moment1 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然 🤔🤔🤔
前端·后端·面试
天问一1 小时前
使用 Vue Router 进行路由定制和调用的示例
前端·javascript·vue.js
韩立学长3 小时前
【开题答辩实录分享】以《基于Vue的非遗文化知识分享平台的设计与实现》为例进行选题答辩实录分享
前端·javascript·vue.js
优弧3 小时前
离开舒适区100天,我后悔了吗?
前端·后端·面试
胡gh3 小时前
css的臂膀,前端动效的利器,还是布局的“隐形陷阱”?
前端·css·html
灵感菇_3 小时前
Flutter Riverpod 完整教程:从入门到实战
前端·flutter·ui·状态管理
用户21411832636023 小时前
紧急修复!Dify CVE-2025-55182 高危漏洞,手把手教你升级避坑
前端