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>
相关推荐
蓝倾3 分钟前
京东批量获取商品SKU操作指南
前端·后端·api
JSLove10 分钟前
常见 npm 报错问题
前端·npm
sunbyte10 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ContentPlaceholder(背景占位)
前端·javascript·css·vue.js·tailwindcss
爱学习的茄子11 分钟前
React Hooks进阶:从0到1打造高性能Todo应用
前端·react.js·面试
知性的小mahua15 分钟前
vue3+canvas实现摄像头ROI区域标记
前端
嘗_31 分钟前
暑期前端训练day5
前端
uncleTom66637 分钟前
前端布局利器:rem 适配全面解析
前端
谦哥40 分钟前
Claude4免费Vibe Coding!目前比较好的Cursor替代方案
前端·javascript·claude
LEAFF1 小时前
如何 测试Labview是否返回数据 ?
前端
Spider_Man1 小时前
🚀 从阻塞到丝滑:React中DeepSeek LLM流式输出的实现秘籍
前端·react.js·llm