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>
相关推荐
Hyyy33 分钟前
理解LLM的基本工作原理:预训练、微调、推理的区别
前端
Gatlin1 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
代码煮茶1 小时前
React 组件封装方法论 —— 以 Todo App 为例
javascript·react.js
Pedantic1 小时前
本地通知(Local Notifications)学习笔记
前端
任沫1 小时前
Agent之Function Call
javascript·人工智能·go
森蓝情丶2 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
爱勇宝2 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员
Pedantic2 小时前
Combine 框架学习笔记
前端
runnerdancer2 小时前
Agent如何加载执行Skill的脚本
前端·agent
yingyima3 小时前
VS Code 正则替换技巧:从凌晨3点的服务器报警开始
前端