1

水平居中

水平居中没有什么好说的啦,对于行内元素使用text-align;对于块级元素使用margin: auto(前提是已经为元素设置了适当的 width 宽度);

垂直居中

单行文本

line-height == height

多行文本

伪元素before/after

<div class="parent">
    <span class="child">etttttttttttttttttttttttttttttttttttttttttttttgdfsffffffffffffffffffffffffffffffffffffffffffffffffff</span>
</div>
.parent {
  height: 250px;
  text-align: center;
  border: 1px solid;
}
.parent:before {
  content: " ";
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
.child {
   width: 200px;
   display: inline-block;
   word-wrap: break-word;
   border: 1px solid;
   vertical-align: middle;
}

行内元素

line-height

<div class="parent">
 <img class="child" src="./images/7.png"/>
</div>
.parent {
  line-height: 200px; 
}
.child {
    vertical-align: middle;
}

伪元素before/after

<div class="parent">
 <img class="child" src="./images/7.png"/>
</div>
.parent {
  height: 200px;
  border: 1px solid;
}
.parent:before {
  content: " ";
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
.child {
    vertical-align: middle;
}

table-cell ie8+

<div class="parent">
 <img class="child" src="./images/7.png"/>
</div>
.parent {
  height: 200px;
  border: 1px solid;
  display: table-cell;
  vertical-align: middle;
}
.child {
  vertical-align: middle;
}

未知宽高

绝对居中+margin:auto

.parent {
   position: relative;
}
.child {
   position: absolute; 
   left: 0; 
   top: 0; 
   right: 0; 
   bottom: 0;
  margin: auto;
}

绝对定位+transform ie9+

.parent {
   position: relative;
}
.child {
   position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}

flex ie10+

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
}

grid ie10+

.parent {
   display: grid;
   justify-content: center;
   align-items: center;
}

已知宽高

负margin

要考虑兼容性

.parent {
   position: relative;
}
.child {
   position: absolute;
  top: 50%;
  left: 50%;
  margin: -height/2 -width/2;
}

padding

.parent {
   padding: (parent.height-child.height)/2  (parent.width-child.width)/2;
}

absolute + calc ie9+

.parent {
   position: relative;
}
.child {
   position: absolute;
  top: calc(50% - height/2 );
  left: calc(50% - height/2 );
}

浮动元素垂直居中

父元素table-cell

#demo {
    width: 300px;
    height: 200px;
    background-color: grey;
    
    display: table-cell;
    vertical-align: middle;
}
.fl {
    float: left;
    width: 50px;
    height: 50px;
    background-color: black;

}

<div id="demo">
    <div class="fl"></div>
</div>

zhouzhou
1.5k 声望76 粉丝

web前端