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>
相关推荐
贺今宵2 分钟前
Vue 3 + Capacitor 使用jeep-sqlite,web端使用本地sqlite数据库
前端·数据库·vue.js·sqlite·web
taocarts_bidfans4 分钟前
Google Indexing API 外贸独立站主动推送收录实战开发
前端·独立站·外贸独立站·taoify
lichenyang45322 分钟前
鸿蒙 Stage 模型到底是什么?一篇讲清 Ability、EntryAbility 和入口文件为什么这么设计
前端
ihuyigui38 分钟前
国际商超零售短信接口
大数据·前端·后端·架构·零售
Yan-英杰38 分钟前
从零玩转搜索引擎 API: 多引擎整合实战
服务器·前端·microsoft
Spider_Man43 分钟前
Claude Code Hooks:给 AI 助手装上"安全带"
前端·ai编程·claude
lichenyang4531 小时前
HarmonyOS 6.0 ArkUI 循环渲染:ForEach、LazyForEach 和 Repeat 到底怎么选?
前端
Captaincc1 小时前
置身钉内:一个 AI 办公产品的理想、失焦与组织困境
前端·程序员
零陵上将军_xdr1 小时前
后端转全栈学习-Day6-JavaScript 基础-4
前端·javascript·学习
梦幻通灵2 小时前
Vue3 Element日期控件置灰明天之后日期
前端·javascript·vue.js