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>
相关推荐
奇奇怪怪的问题21 小时前
学习ts笔记(二):属性修饰符,泛型,接口
前端·typescript
明月_清风21 小时前
全面了解 Vercel:前端开发者的高效武器库与实战指南
前端·next.js
NiceCloud喜云21 小时前
Claude API PDF 文档问答实战:从原生解析到分页引用的完整方案
java·服务器·前端·网络·数据库·人工智能·pdf
东方小月1 天前
vibecoding实战:用 Claude Code 从0到1开发一个 Claude Code
前端·人工智能·架构
marsh02061 天前
54 openclaw钩子函数使用:在框架生命周期中注入自定义逻辑
java·前端·spring
TechExplorer3651 天前
npm install 日志目录
前端·npm·node.js
笔优站长1 天前
从 Vue 2 到 Vue 3:我把 vue-aliplayer-v2 重构成了一个更现代的阿里云播放器组件
前端·vue.js
蓝银草同学1 天前
新手指南:快速理清独立仓库 Java 8 多模块项目依赖并运行
前端·后端
蓝银草同学1 天前
前端转 Java,第一篇看懂 pom.xml:Maven 依赖管理从入门到不懵
前端·后端
彦为君1 天前
JavaSE-11-网络编程(详细版)
java·前端·网络·ai·ai编程