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>
相关推荐
IT_陈寒3 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
天衍四九-3 小时前
【无标题】
前端·spring boot·mysql·nginx·docker
广州华水科技3 小时前
2026年单北斗GNSS变形监测系统推荐榜单,解锁GNSS位移监测新高度
前端
xcyxiner3 小时前
DicomViewer24 修复编译bug(window test 失败)
前端·qt
linux_cfan3 小时前
videojs v10 源代码系列解读:34 · `createComposition`:类型安全的冲突检测
前端·安全
Bruce_Liuxiaowei4 小时前
网页版 DeepSeek “harness desktop“ WebGL 上下文创建失败排查实录
开发语言·javascript·webgl
utmhikari4 小时前
【AI原生】借助AI之力优化个人博客前端样式
前端·css·hexo·next·个人博客·ai-native·vibe coding
小凯在掘金5 小时前
为什么箭头函数不能作为构造函数?
前端·javascript
可乐鸡翅yeah_5 小时前
网页端 M3U8 播放器性能监控,怎么看播放卡顿指标
javascript·ffmpeg·音视频·safari·m3u8