css系列之水平垂直居中

水平居中

水平居中沒有什麼好說的啦,對於行內元素使用text-align;對於塊級元素使用margin: auto(前提是已經爲元素設置了適當的 width 寬度);javascript

垂直居中

單行文本

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

要考慮兼容性java

.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>
相關文章
相關標籤/搜索