CSS:如何实现垂直居中

63 阅读2分钟

我们在编辑页面的时候,通常都会用到水平居中和垂直居中,水平居中很好处理,就是设定margin:0 auto;;或者是 text-align: center;,就可以轻松的解决掉水平居中的问题,但垂直居中最麻烦的,下面就是我使用的垂直居中的方式。

垂直居中

  • 如果 .parentheight 不写,只需要 padding: 10px 0; 就能将 .child 垂直居中。

  • 如果 .parentheight 写死了,就很难把 .child 居中,下面就是将 height 固定死的方法。

  • height能不写死就不写死

使用flex布局

HTML

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

CSS

.parent{
  border: 1px solid red;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.child{
  border: 10px solid green;
}

image.png

使用绝对定位 margin: auto;

HTML

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

CSS

.parent{
  border: 1px solid red;
  height: 400px;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  width: 100px;
  height: 100px;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

image.png

绝对定位和 transform: translate(-50%,-50%);

HTML

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

CSS

.parent{
  border: 1px solid red;
  height: 400px;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%)
}

image.png

绝对定位和 margin-top: -50%;

HTML

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

CSS

.parent{
  border: 1px solid red;
  height: 400px;
  position: relative;
}
.child{
  border: 1px solid green;
  position: absolute;
  width: 200px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin-left: -100px;
  margin-top: -50px;
}

image.png

table 自带功能

HTML

 <table class="parent">
    <tr>
      <td class="child">你好</td>
    </tr>
  </table>

CSS

.parent{
  border: 1px solid red;
  height: 400px;
}
.child{
  border: 1px solid green;
}

image.png

使用display: table;vertical-align: middle;

就是把div标签伪装成table标签

vertical-align 属性只对拥有 valign 特性的 html 元素起作用,例如表格元素中的 <td> <th> 等等,而像 <div> <span> 这样的元素是不行的。

HTML

<div class="table">
      <div class="td">
        <div class="child">
          你好
        </div>
    </div>
  </div>

CSS

div.table{
  display: table;
  border: 1px solid red;
  height: 400px;
}

div.tr{
  display: table-row;
  border: 10px solid green;
}

div.td{
  display: table-cell;
  border: 1px solid blue;
  vertical-align: middle;
}
.child{
  border: 10px solid black;
}

image.png

100% 高度的 after before 加上 inline block

HTML

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

CSS

.parent{
  border: 3px solid red;
  height: 600px;
  text-align: center;
}

.child{
  border: 3px solid black;
  display: inline-block;
  width: 300px;
  vertical-align: middle;
}

.parent:before{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.parent:after{
  content:'';
  outline: 3px solid red;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

image.png