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 分钟前
useCallback 和 useMemo,什么时候用才是有效的?
前端·react.js
星哥说事15 分钟前
跨平台开源笔记神器,用DeepSeek写笔记 , 效率翻倍
前端
喜欢你,还有大家43 分钟前
FTP文件传输服务
linux·运维·服务器·前端
该用户已不存在1 小时前
你没有听说过的7个Windows开发必备工具
前端·windows·后端
Bi1 小时前
Dokploy安装和部署项目流程
运维·前端
普通网友1 小时前
前端安全攻防:XSS, CSRF 等防范与检测
前端·安全·xss
携欢1 小时前
PortSwigger靶场之Reflected XSS into attribute with angle brackets HTML-encoded通关秘籍
前端·xss
小爱同学_1 小时前
React知识:useState和useRef的使用
前端·react.js
再学一点就睡1 小时前
双 Token 认证机制:从原理到实践的完整实现
前端·javascript·后端
wallflower20201 小时前
滑动窗口算法在前端开发中的探索与应用
前端·算法