CSS 居中

html 复制代码
<div class="father">
  <div class="child"></div>
</div>

1. Flex(推荐)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  display: flex;                /* flex 方法 */
  justify-content: center;      /* flex 方法 */
  align-items: center;          /* flex 方法 */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
}

2. Grid(推荐)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  display: grid;            /* flex 方法 */
  place-items: center;      /* flex 方法 */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
}

3. 绝对定位 + Transform

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  position: relative;                /* 绝对定位 + Transform */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;                /* 绝对定位 + Transform */
  top: 50%;                          /* 绝对定位 + Transform */
  left: 50%;                         /* 绝对定位 + Transform */
  transform: translate(-50%,-50%);   /* 绝对定位 + Transform */
}

4. Margin Auto(需已知尺寸)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  position: relative;          /* Margin Auto */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;          /* Margin Auto */
  top: 0;                      /* Margin Auto */
  left: 0;                     /* Margin Auto */
  right: 0;                    /* Margin Auto */
  bottom: 0;                   /* Margin Auto */
  margin: auto;                /* Margin Auto */
}

5. 行高方法(适用于单行文本)

css 复制代码
.father {
  width: 300px;                /* 行高方法 */ 
  height: 300px;               /* 行高方法 */ 
  background-color: #f0f8f8;
}
.child {
  line-height: 300px;          /* 行高方法 */ 
  text-align: center;          /* 行高方法 */ 
  color: #2f4f4f;
}
相关推荐
yaaakaaang1 分钟前
(八)前端,如此简单!---五组结构
前端·javascript
我是若尘5 分钟前
我的需求代码被主干 revert 了,接下来我该怎么操作?
前端·后端·代码规范
魁首27 分钟前
Claude Code 源码泄露的背后,到底与Codex,Gemini 有啥不一样?
前端·openai·claude
攀登的牵牛花28 分钟前
程序员失业论,被 SWE-CI 一组数据打醒:真正先被替代的是低质量交付
前端·github
BumBle1 小时前
Vue项目中实现路由守卫自动取消Pending请求
前端
gCode Teacher 格码致知1 小时前
Javascript提高:get和post等请求,对于汉字和空格信息进行编码的原则-由Deepseek产生
开发语言·前端·javascript·node.js·jquery
竹林8181 小时前
从ethers.js迁移到Viem:我在一个DeFi项目前端重构中踩过的坑
前端·javascript
像我这样帅的人丶你还1 小时前
从交稿到甩锅预防:AI 前端流水线
前端·ai编程
想想弹幕会怎么做1 小时前
如何构建一颗可交互的ui树?
前端
程序员陆业聪2 小时前
我见过的最反直觉的 Android 架构问题:UseCase 越多,项目越烂
前端