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;
}
相关推荐
UXbot2 小时前
AI原型设计工具如何支持团队协作与快速迭代
前端·交互·个人开发·ai编程·原型模式
ZC跨境爬虫3 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
PieroPc4 小时前
CAMWATCH — 局域网摄像头监控系统 Fastapi + html
前端·python·html·fastapi·监控
巴巴博一5 小时前
2026 最新:Trae / Cursor 一键接入 taste-skill 完整教程(让 AI 前端告别“AI 味”)
前端·ai·ai编程
kyriewen5 小时前
半夜三点线上崩了,AI替我背了锅——用AI排错,五分钟定位三年老bug
前端·javascript·ai编程
kyriewen6 小时前
我让 AI 当了 24 小时全年无休的“毒舌考官”
前端·ci/cd·ai编程
hexu_blog6 小时前
vue+java实现图片批量压缩
java·前端·vue.js
IT_陈寒6 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
lifejump6 小时前
Empire(帝国)CMS 7.5 XSS注入
前端·安全·xss
无风听海7 小时前
OAuth 2.0 前端通道与后端通道深入剖析
前端·oauth