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>
相关推荐
浮桥8 分钟前
vue3实现pdf文件预览 - vue-pdf-embed
前端·vue.js·pdf
七夜zippoe19 分钟前
前端开发中的难题及解决方案
前端·问题
Hockor1 小时前
用 Kimi K2 写前端是一种什么体验?还支持 Claude Code 接入?
前端
杨进军1 小时前
React 实现 useMemo
前端·react.js·前端框架
海底火旺1 小时前
浏览器渲染全过程解析
前端·javascript·浏览器
你听得到112 小时前
揭秘Flutter图片编辑器核心技术:从状态驱动架构到高保真图像处理
android·前端·flutter
驴肉板烧凤梨牛肉堡2 小时前
浏览器是否支持webp图像的判断
前端
Xi-Xu2 小时前
隆重介绍 Xget for Chrome:您的终极下载加速器
前端·网络·chrome·经验分享·github
摆烂为不摆烂2 小时前
😁深入JS(九): 简单了解Fetch使用
前端
杨进军2 小时前
React 实现多个节点 diff
前端·react.js·前端框架