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;
}
相关推荐
前端炒粉2 分钟前
fetch+readablestream(Streamable)流式输出
java·服务器·前端
风骏时光牛马6 分钟前
AIRAG服务异常监控告警
前端
大厂码农老A10 分钟前
汤森路透的座上宾?Qwen3.5-397B-A17B到底有什么本事?
前端·人工智能·后端
静开17 分钟前
Skills和MCP 到底什么区别
前端·人工智能
伯远医学23 分钟前
RIP-seq 高分文献案例分享
java·前端·javascript·人工智能·算法·eclipse·html
hunterandroid23 分钟前
[鸿蒙从零到一] LazyForEach 复用陷阱与 KeyGenerator 设计实战
前端
Hilaku29 分钟前
Web Components 为什么火不起来?
前端·javascript·程序员
Liora_Yvonne34 分钟前
从数据库到 Vue 页面:用 LY Fullstack 完成第一个真实全栈业务模块
前端·后端·nestjs
hunterandroid40 分钟前
自定义 View 绘制与触摸冲突:从滑动卡顿到事件分发闭环
android·前端
vancece44 分钟前
JS实现堆 & 215.数组中的第K个最大元素
java·前端·javascript