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>
相关推荐
a111776几秒前
模仿刀剑神域风格 作品集网页
前端·开源
a1117764 分钟前
Elemental Sandbox(元素沙盒)-Three.js 游戏技能特效
前端·开源
用户69371750013849 分钟前
前阵子刷屏的 Ox-Alpha 真身揭晓!GLM-5.3-Flash 上线,这价格真的杀疯了
前端·后端·github
四千岁15 分钟前
抓包LangChain-了解LangChain的原理
前端·javascript·后端
南雨北斗15 分钟前
TS方式构建Vue3 toast组件(一)
前端
IT小白杨17 分钟前
2026游戏工作室环境隔离指南:从设备指纹到移动IP的部署实践
前端·经验分享·网络协议·tcp/ip·游戏·安全架构·指纹浏览器
用户2986985301421 分钟前
使用 JavaScript 在 React 中实现 Word 转 PDF
前端·javascript·react.js
hunterandroid1 小时前
[鸿蒙从零到一] @Observed 与 @ObjectLink 深层响应陷阱与最佳实践
前端
hunterandroid1 小时前
[鸿蒙从零到一] ArkTS 装饰器原理与自定义装饰器实践
前端
hunterandroid1 小时前
ContentProvider 跨进程数据共享实战
android·前端