CSS 居中

html 复制代码
<div class="father">
  <div class="child"></div>
</div>

1. Flex(推荐)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  display: flex;                /* flex 方法 */
  justify-content: center;      /* flex 方法 */
  align-items: center;          /* flex 方法 */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
}

2. Grid(推荐)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  display: grid;            /* flex 方法 */
  place-items: center;      /* flex 方法 */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
}

3. 绝对定位 + Transform

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  position: relative;                /* 绝对定位 + Transform */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;                /* 绝对定位 + Transform */
  top: 50%;                          /* 绝对定位 + Transform */
  left: 50%;                         /* 绝对定位 + Transform */
  transform: translate(-50%,-50%);   /* 绝对定位 + Transform */
}

4. Margin Auto(需已知尺寸)

css 复制代码
.father{
  width: 300px;
  height: 300px;
  background-color: red;
  position: relative;          /* Margin Auto */
}
.child{
  width: 100px;
  height: 100px;
  background-color: blue;
  position: absolute;          /* Margin Auto */
  top: 0;                      /* Margin Auto */
  left: 0;                     /* Margin Auto */
  right: 0;                    /* Margin Auto */
  bottom: 0;                   /* Margin Auto */
  margin: auto;                /* Margin Auto */
}

5. 行高方法(适用于单行文本)

css 复制代码
.father {
  width: 300px;                /* 行高方法 */ 
  height: 300px;               /* 行高方法 */ 
  background-color: #f0f8f8;
}
.child {
  line-height: 300px;          /* 行高方法 */ 
  text-align: center;          /* 行高方法 */ 
  color: #2f4f4f;
}
相关推荐
两个西柚呀6 小时前
未在props中声明的属性
前端·javascript·vue.js
子伟-H58 小时前
App开发框架调研对比
前端
桃子不吃李子8 小时前
axios的二次封装
前端·学习·axios
SteveJrong9 小时前
面试题 - JavaScript
前端·javascript·面试·ecmascript·基础·找工作·红宝书
阿金要当大魔王~~9 小时前
uniapp 页面标签 传值 ————— uniapp 定义 接口
前端·javascript·uni-app·1024程序员节
全栈软件开发9 小时前
uniapp三端影视源码苹果cms自动采集电影视频网站源码前端源码带VIP
前端·uni-app·影视源码
chxii9 小时前
10.4FormData :前端文件上传与表单数据处理的核心工具
前端
AntBlack10 小时前
不当韭菜 : 好像真有点效果 ,想藏起来自己用了
前端·后端·python
楊无好10 小时前
react中props的使用
前端·react.js·前端框架
一个处女座的程序猿O(∩_∩)O10 小时前
Vue-Loader 深度解析:原理、使用与最佳实践
前端·javascript·vue.js