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>
相关推荐
咖啡の猫1 分钟前
Vue收集表单数据
前端·javascript·vue.js
知识分享小能手10 分钟前
uni-app 入门学习教程,从入门到精通, uni-app常用API的详细语法知识点(上)(5)
前端·javascript·vue.js·学习·微信小程序·小程序·uni-app
林恒smileZAZ17 分钟前
CSS3 超实用属性:pointer-events (可穿透图层的鼠标事件)
前端·计算机外设·css3
云中雾丽25 分钟前
flutter中 NotificationListener 详细使用指南
前端
大杯咖啡25 分钟前
一篇文章搞懂,浏览器强缓存以及协商缓存
前端·javascript
王六岁26 分钟前
# 🐍 前端开发 0 基础学 Python 入门指南: Python 元组和映射类型深入指南
前端·javascript·python
_志哥_28 分钟前
多行文本超出,中间显示省略号的终极方法(适配多语言)
前端·javascript·vue.js
王六岁29 分钟前
# 🐍 前端开发 0 基础学 Python 入门指南:常用的数据类型和列表
前端·javascript·python
1_2_3_30 分钟前
神级JS API,谁用谁好用
前端·javascript
冬至已至33 分钟前
AI 时代的自动化信息获取与整合
前端