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>
相关推荐
奕鼎竜瑆4 小时前
Chrome 插件开发实战指南:从入门到发布
前端·chrome
广州华水科技4 小时前
水库北斗GNSS变形监测系统及单北斗形变监测一体机应用解析
前端
anew___6 小时前
《从零手写操作系统 (20):ELF加载器——让OS读懂现代编译器》
java·服务器·前端
ss2736 小时前
AI全栈实战 | 2.3-01 组件库实战:Element Plus 怎么搭出专业界面,过度封装为什么成维护负担
前端·javascript·elementui·vue
对空六课6 小时前
动态按钮ID变化时的稳定埋点标识设计
前端·数据分析
福兮说6 小时前
URL 编码的七个坑:c++ 传到后端变空格、%25 套娃、截断 emoji 直接报错
开发语言·前端·javascript·node.js·url
吴声子夜歌6 小时前
Nginx应用与运维——Nginx Web服务应用实战(Python网站的搭建)
运维·前端·nginx
小的时候可菜了6 小时前
JS 异步的本质:从单线程到 thenable(一条进化链)
开发语言·前端·javascript
liangshanbo12156 小时前
Webpack vs Vite 底层原理高频追问的问题
前端·webpack·node.js
web打印社区7 小时前
Windows 网页静默打印设置步骤:客户端、防火墙与联调清单
开发语言·前端·javascript·chrome·pdf·ecmascript