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>
相关推荐
刘一说5 分钟前
ES6+核心特性全面浅析
java·前端·es6
lcc1878 分钟前
CSS 浮动
css
kirinlau11 分钟前
Vue.observable实现vue原生轻量级状态管理详解
前端·javascript·vue.js
严文文-Chris12 分钟前
RAG关键技术要点详解
java·服务器·前端
自然 醒13 分钟前
elementUI的select下拉框如何下拉加载数据?
前端·javascript·elementui
我没想到原来他们都是一堆坏人14 分钟前
常用npm源与nrm
前端·npm·node.js
编代码的小王17 分钟前
【无标题】
前端·css
im_AMBER26 分钟前
React 20 useState管理组件状态 | 解构 | 将事件处理函数作为 props 传递 | 状态提升
前端·javascript·笔记·学习·react.js·前端框架
小oo呆27 分钟前
【自然语言处理与大模型】LangChainV1.0入门指南:核心组件Tools
前端·javascript·easyui
be or not to be30 分钟前
HTML 与 CSS 基础入门笔记
css·笔记·html