css实现居中

基础代码

html 复制代码
<div class="box">
  <div class="content"></div>
</div>

css实现居中的几种方式

1、flex布局(水平垂直)

html 复制代码
.box {
  width: 200px;
  height: 200px;
  background-color: pink;
  display: flex;
  justify-content: center;
  align-items: center;
}
.content {
  width: 100px;
  height: 100px;
  background-color: lawngreen;
}

2、margin:auto;(水平)

html 复制代码
.box {
  width: 200px;
  height: 200px;
  background-color: pink;
}
.content {
  width: 100px;
  height: 100px;
  background-color: lawngreen;
  margin: auto;
}

3、固定定位+transform(水平垂直)

html 复制代码
.box {
  width: 200px;
  height: 200px;
  background-color: pink;
  position: relative;
}
.content {
  width: 100px;
  height: 100px;
  background-color: lawngreen;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

4、vertical-align: middle;(垂直)

html 复制代码
.box {
  width: 200px;
  height: 200px;
  background-color: pink;
}
.content {
  width: 100px;
  height: 100px;
  background-color: lawngreen;
}
.box::after, .content{
  display:inline-block;
  vertical-align:middle;
}
.box::after{
  content:'';
  height:100%;
}

5、line-heihgt + text-align

html 复制代码
.text-box {
  width: 100px;
  height: 50px;
  background-color: aquamarine;
  text-align:center;
}
.text-box span {
  line-height: 50px;
}

<div class="text-box"><span>1</span></div>
相关推荐
WL_arm11 分钟前
Vibe Coding(氛围编程)入门
javascript·css·人工智能·html5
艾醒(AiXing-w)13 分钟前
LangChain 1.0 入门(二):LangChain 全模型标准化接入最佳实践(小白参数详解版)
前端·javascript·langchain
计算机魔术师41 分钟前
我看了 Hugging Face 的 Daily Papers,发现这件事
前端
yu俞娥宝1 小时前
Codex官网前端可抄吗?技术拆解、风险边界与合规借鉴方案
前端
捧 花2 小时前
FastAPI 基础语法:从一个完整接口理解 Web API 的设计
前端·python·fastapi·middleware
Hilaku2 小时前
一行 CSS 新特性干掉 20 行 JavaScript ?
前端·javascript·程序员
JarvanMo2 小时前
AI 写代码暴增 161 倍,移动开发有没有变得更差?
前端
梦曦i2 小时前
RouterLink v2.5.0:H5端原生能力全面回归
前端·uni-app
小林ixn2 小时前
React + Zustand + JWT:从零实现登录鉴权与请求拦截
前端·react.js·前端框架
葡萄城技术团队3 小时前
下拉多选类型单元格:在 SpreadJS 里接入 xm\-select
前端