CSS垂直居中

居中元素宽高已知

1.absolute  + margin auto

注意:父元素与当前元素的宽高已知

.parent{
  position: relative;
  width: 500px;
  height: 500px;
  border: 1px solid blue;
}
 
.child{
  background: green;
  width: 200px; 
  height: 200px;
  /* 核心代码 */
  position:absolute;
  top: 0; 
  bottom: 0; 
  left: 0; 
  right: 0;
  margin: auto;
}

2.absolute + 负 margin

注意:负 margin 是基于自身的高度和宽度来进行位移的(设置自身的 -1/2)

.parent{
  position:relative;
  width: 500px;
  height: 500px;
  border: 1px solid blue;
}
 
.child{
  background: green;
  width: 200px; 
  height: 200px;
  /* 核心代码 */
  position:absolute;
  top: 50%; 
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
}

3.absolute + calc

注意:使用CSS3的一个计算函数来进行计算(相当于负margin的简化版)

.parent{
  position:relative;
  width: 500px;
  height: 500px;
  border: 1px solid blue;
}
 
.child{
  background: green;
  width: 200px; 
  height: 200px;
  /* 核心代码 */
  position:absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
}

居中元素宽高未知

1、absolute + transform

注意:transform的translate 属性值如果是一个百分比,那么这个百分比是基于自身的宽高进行计算

.parent{
  position: relative;
  width: 500px;
  height: 500px;
  border: 1px solid blue;
}
 
.child{
  background: green;
  /* 核心代码 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

2、line-height + vertical-align

把当前元素设置为行内元素,然后通过设置父元素的text-align:center来实现水平居中;同时通过设置当前元素的vertical-align:middle来实现垂直居中;最后设置当前元素的line-height:initial来继承父元素的line-height

.parent{
  width: 500px;
  border: 1px solid blue;
  /* 核心代码 */
  line-height: 500px;
  text-align: center;
}
 
.child{
  background: green;
  /* 核心代码 */
  display: inline-block;
  vertical-align: middle;
  line-height: initial;
}

3、table 表格元素(不推荐)

通过经典的table来进行布局(不推荐)

<table>
  <tbody>
    <tr>
      <td class="parent">
        <div class="child"></div>
      </td>
    </tr>
  </tbody>
</table>
 
<style>
  .parent{
    width: 500px;
    height: 500px;
    border: 1px solid blue;
    /* 核心代码 */
    text-align: center;
  }
  .child{
    background: green;
    /* 核心代码 */
    display: inline-block;
  }
</style>

4、css-table (display:table-cell)

不写table元素,也可以使用table的特性,需使用css-table(display:table-cell)

.parent{
  width: 500px;
  height: 500px;
  border: 1px solid blue;
  /* 核心代码 */
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
 
.child{
  background: green;
  /* 核心代码 */
  display: inline-block;
}

5、flex 布局(推荐)

.parent{
  width: 500px;
  height: 500px;
  border: 1px solid blue;
  /* 核心代码 */
  display: flex;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
}
.child{
  background: green;
}

justify-content:设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;

align-items:设置或检索弹性盒子元素在侧轴(纵轴)方向上的对齐方式。

 

posted @ 2022-01-05 10:14  无何不可88  阅读(201)  评论(0)    收藏  举报