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;
}
相关推荐
程序员爱钓鱼1 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
PineappleCoder1 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
JIngJaneIL2 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码2 小时前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_2 小时前
列表渲染(v-for)
前端·javascript·vue.js
JustHappy3 小时前
「chrome extensions🛠️」我写了一个超级简单的浏览器插件Vue开发模板
前端·javascript·github
Loo国昌3 小时前
Vue 3 前端工程化:架构、核心原理与生产实践
前端·vue.js·架构
sg_knight3 小时前
拥抱未来:ECMAScript Modules (ESM) 深度解析
开发语言·前端·javascript·vue·ecmascript·web·esm
LYFlied3 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展