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 分钟前
前端 Jest 单元测试零基础实战:模板、提效、避坑、面试题(Vue 项目可用)
前端·vue.js·单元测试
和blue一起变得更好5 分钟前
周三:Vue3高级组件特性
前端·javascript·vue.js
happyprince8 分钟前
10-Hugging Face Transformers 量化系统深度分析
java·前端·数据库
AskHarries9 分钟前
如何使用 OpenClaw Skill
前端
AI周红伟21 分钟前
Agent Skills生产级Skills 案例实操-周红伟
前端·chrome·react.js·langchain
用户862841295494429 分钟前
Flutter rxflare 响应式进阶:Map/List 精准字段更新(高性能实战)
前端·flutter
横木沉31 分钟前
高并发场景下的前端缓存与降级策略
大数据·前端·缓存
我命由我1234539 分钟前
VSCode - VSCode 自定义折叠区域
前端·javascript·ide·vscode·前端框架·编辑器·js
cc.ChenLy44 分钟前
Lottie-Web 技术指南:让动画开发更简单高效
前端
bug总结1 小时前
前端流程图vueflow
前端·流程图