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>
相关推荐
Rverdoser13 分钟前
代理服务器运行速度慢是什么原因
开发语言·前端·php
航Hang*31 分钟前
前端项目2-01:个人简介页面
前端·经验分享·html·css3·html5·webstorm
MaisieKim_44 分钟前
python与nodejs哪个性能高
前端·python·node.js
水煮白菜王1 小时前
深入理解 Webpack 核心机制与编译流程
前端·webpack·node.js
梦幻通灵1 小时前
Excel分组计算求和的两种实现方案
前端·excel
whatever who cares2 小时前
CSS3 伪类和使用场景
前端·css·css3
水银嘻嘻2 小时前
Web 自动化之 HTML & JavaScript 详解
前端·自动化·html
天天打码2 小时前
Lynx-字节跳动跨平台框架多端兼容Android, iOS, Web 原生渲染
android·前端·javascript·ios
大G哥3 小时前
项目中利用webpack的require.context实现批量引入/导入图片
前端·webpack·node.js
有事没事实验室3 小时前
CSS 盒子模型与元素定位
前端·css·开源·html5