纯css实现垂直居中

2018-11-05  本文已影响0人  zhangxt456

方法1: display: table-cell

html结构:

<div class="parent">
      <span>垂直居中</span>
 </div>

css:

.parent{
      display: table-cell;
      height: 100px;
      vertical-align: middle;
      background: #eeb3b3;
}
image.png

方法2:display: flex

html结构:

<div class="parent">
      <span>垂直居中</span>
 </div>

css:

.parent{
      display: flex;
      height: 100px;
      align-items: center;
      background: #eeb3b3;
}

方法3:绝对定位加负边距

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      position: relative;
      height: 100px;
      background: #eeb3b3;
}
.son{
      position: absolute;
      height: 50px;
      top:50%;
      margin-top:-25px;
      background: #fff;
}

方法4:绝对定位0

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      position: relative;
      height: 100px;
      background: #eeb3b3;
}
.son{
      width: 50%;
      height: 50%; 
      background: #fff;
      overflow: auto; 
      margin: auto; 
      position: absolute; 
      top: 0; left: 0; bottom: 0; right: 0; 
}

方法5:translate

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      position: relative;
      height: 100px;
      background: #eeb3b3;
}
.son{
      position: absolute;
      top:50%;
      left:50%;
      width:100%;
      transform:translate(-50%,-50%);
      text-align: center;
      background: #fff;
}

方法6:display:inline-block

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      height: 100px;
      background: #eeb3b3;
      text-align:center;
      font-size:0;
}
.son{
      vertical-align:middle;
      display:inline-block;
      font-size:16px;
}
.parent::after{
      content:'';
      width:0;
      height:100%;
      display:inline-block;
      vertical-align:middle;
}

方法7:display:flex和margin:auto

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      height: 100px;
      background: #eeb3b3;
      display: flex;
      text-align: center;
}
.son{
      margin: auto;
}

方法8:display:-webkit-box

html结构:

<div class="parent">
      <span class="son">垂直居中</span>
 </div>

css:

.parent{
      display: -webkit-box;
      -webkit-box-pack:center;
      -webkit-box-align:center;
      -webkit-box-orient: vertical;
      text-align: center
}
上一篇下一篇

猜你喜欢

热点阅读