css系列之水平垂直居中

水平居中

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

垂直居中

单行文本

line-height == height

多行文本

伪元素before/after

etttttttttttttttttttttttttttttttttttttttttttttgdfsffffffffffffffffffffffffffffffffffffffffffffffffff
.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

 
.parent { line-height: 200px; } .child { vertical-align: middle; }

伪元素before/after

 
.parent { height: 200px; border: 1px solid; } .parent:before { content: " "; height: 100%; display: inline-block; vertical-align: middle; } .child { vertical-align: middle; }

table-cell ie8+

 
.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;

}

你可能感兴趣的:(css,垂直居中,水平居中)