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>
相关推荐
liangshanbo12153 小时前
高级前端面试题:package.json 常见字段
前端·json
CappuccinoRose4 小时前
输入事件进阶
前端·javascript·输入事件
liangshanbo12155 小时前
面试题:前端工程化中 Tree Shaking的原理是什么?
前端·treeshaking
补码缩写6 小时前
视频跳转触发了seeked,画面就到位了吗
前端
库拉镜像AI牛牛6 小时前
漫剧工作室量产方案:依托知漫剧 AI 短剧降本增效
大数据·服务器·前端·人工智能·语音识别
不可能片场6 小时前
内容运营自动化 用相似度拦住撞车选题
前端·electron
静默回滚6 小时前
视频进度条跳回去,先别改事件监听
前端
Lank_M6 小时前
MP4和WebM导出后为何起播与拖动不同
前端
用户5508492902566 小时前
前端本地存储怎么选:Cookie、localStorage、sessionStorage、IndexedDB 的取舍
前端
用户5508492902566 小时前
Git 日常命令与分支协作流程:从提交到合并的实战梳理
前端