11种垂直居中

垂直居中主要分为了两种类型:居中元素宽高已知 和 居中元素宽高未知,那么我们就结合这两种类型来一一做举例。

 

 一、居中元素宽高已知

1. absolute + margin auto

.parent{
  position: relative;
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
}

.child{
  background: tomato;
  width: 50vw; height: 50vh;
  /* 核心代码 */
  position:absolute;
  top: 0; bottom: 0; left: 0; right: 0;
  margin: auto;
}

2.  absolute + 负 margin

.parent{
  position:relative;
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
}

.child{
  background: tomato;
  width: 100px; height: 100px;
  /* 核心代码 */
  position:absolute;
  top: 50%; left: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

3. absolute + calc

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  /* 核心代码 */
  position:relative;
}

.child{
  background: tomato;
  width: 200px; height: 200px;
  /* 核心代码 */
  position:absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
}

 

二、居中元素宽高未知

4. absolute + transform

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  /* 核心代码 */
  position:relative;
}

.child{
  background: tomato;
  /* 核心代码 */
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5. line-height + vertical-align

.parent{
  width: 90vw;
  border: 3px solid steelblue;
  /* 核心代码 */
  line-height: 500px;
  text-align: center;
}

.child{
  background: tomato;
  /* 核心代码 */
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
}

6.  css-table 表格样式

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  /* 核心代码 */
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.child{
  background: tomato;
  /* 核心代码 */
  display: inline-block;
}

7. flex 布局(一)

.parent {
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  
  /* 核心代码 */
  display: flex;
  justify-content: center;
 align-items: center;
}
.child{
  background: tomato;
}

8. flex + margin auto(二)

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  
  /* 核心代码 */
  display: flex;
}

.child{
  background: tomato;
  
  /* 核心代码 */
  margin: auto;
}

9.  grid 网格布局 (一)

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  /* 核心代码 */
  display: grid;
  align-items: center;
  justify-content: center;
}

.child{
  background: tomato;  
}

10. grid 网格布局 (二)

.parent{
  width: 90vw;
  height: 90vh;
  border: 3px solid steelblue;
  /* 核心代码 */
  display: grid
}

.child{
  background: tomato;
  /* 核心代码 */
  align-self: center;
  justify-self: center;
}

 

三、总结

在学习了上面的 11 种垂直居中布局方法后,简单概括一下

  • 如果你的项目在 PC 端有兼容性要求并且宽高固定,推荐使用 absolute + 负 margin 方法实现;
  • 如果你的项目在 PC 端有兼容性要求并且宽高不固定,推荐使用 css-table 方式实现;
  • 如果你的项目在 PC 端无兼容性要求 ,推荐使用 flex 实现居中,当然不考虑 IE 的话,grid 也是个不错的选择;
  • 如果你的项目在移动端使用 ,那么推荐你使用 flex ,grid 也可作为备选。

 

源自:https://juejin.cn/post/6991465721565806605

posted @ 2022-08-11 11:36  行走的蒲公英  阅读(97)  评论(0编辑  收藏  举报