01_css垂直居中的几种实现方法

一、position 子元素已知宽度

  • 父元素设置为:position: relative;
  • 子元素设置为:position: absolute;

要点:子元素距上50%,距左50%,外边距设置为自身宽高的一半

<div class="parent">
    <div class="child"></div>
</div>

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  position: relative;
}
.child {
  background: #00f;
  width: 200px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -100px;
}

二、position+transform 子元素已知宽度

  • 父元素设置为:position: relative;
  • 子元素设置为:position: absolute;

要点:子元素添加 transform: translate(-50%,-50%);

<div class="parent">
  <div class="child"></div>
</div>

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  position: relative;
}
.child {
  background: #00f;
  width: 200px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

三、flex布局

  • 父元素可不设置宽高
  • 子元素必须设置宽高

要点:父元素添加 display: flex; justify-content: center; align-items: center;

<div class="parent">
  <div class="child"></div>
</div>

.parent {
  background: #f00;
  width: 400px;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child {
   background: #00f;
   width: 200px;
   height: 100px;
}

四、table-cell布局

  • 外层元素设置为 display: table;
  • 中间元素设置为 display: table-cell;
  • 内层元素设置为 display: inline-block;

要点:

  • 三层元素嵌套
  • 中间元素的table-cell相当于表格的td,td为行内元素,所以需要再嵌套一层
  • 内嵌元素必须设置 display: inline-block;
  • 中间元素table-cell的背景色会覆盖父元素的背景色
<div class="box">
    <div class="content">
        <div class="inner"></div>
    </div>
</div>

.box {
    background: #f00;
    width: 400px;
    height: 400px;
    display: table;
}
.content {
    background: #00f;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.inner {
    background: #000;
    display: inline-block;
    width: 200px;
    height: 100px;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容