以前學習垂直居中的時候在網上找了不少方法,看的我眼花撩亂,一直想着整理一下思路,透過那些紛繁的招式看到本質。
首先明確一下概念:面試
理解了以上三點,就基本能看懂各類垂直居中方法了瀏覽器
這種方法的意思是先把子元素margin和父元素padding的距離置爲0,能夠理解爲子元素和父元素之間沒有空隙,而後把margin置爲auto,margin平分子元素和父元素之間的距離,也就是說子元素並非真正意義的居中,只是子元素中間的內容居中了,子元素和父元素之間的距離是計算機自動計算的(平分);注意這個方法需配合子元素position:absolute使用,由於默認狀況下,margin:auto只對上下起做用,對左右不起做用,加上position使元素脫離標準流,margin:auto可識別佈局
<div class="father"> <div class="son"> </div> </div>
.father{ width:400px; height:400px; background-color:pink; position:relative; } .son{ width:100px; height:100px; background-color:red; position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; }
這種方法適用於不知道父元素寬高的狀況下(面試官可能會這樣問呢)。這種方法是經過先把元素定位到父元素的百分之五十的位置top:50%;left:50%;看下圖:
學習
注意此時子元素的左上角在父元素中間,整個子元素處於父元素右下四分之一的左上角,而後經過transform:translate(-50%,-50%),使子元素相對自身移動百分之五十,這樣子元素就居中啦。須要注意的是自元素中要寫定位position:relative;這樣才能根據父元素識別到定位的基點。spa
<div class="father"> <div class="son"> </div> </div>
.father{ width:500px; height:500px; background-color:pink; /*position:relative;*/ } .son{ width:100px; height:100px; background-color: red; position:relative; top:50%; left:50%; transform:translate(-50%,-50%); }
兩個小栗子講完了,你明白了麼?文章末尾,再送兩個小栗子(#^.^#)code
當一個div裏沒有內容時高度爲0,當有內容好比文字時,div就有了高度,難道是文字把div撐開了?其實不是,這個高度是由元素的line-height決定的。當把line-height設置爲該div的高度時,div中的文字就居中顯示了。代碼很簡單orm
<div class="line"> qqqqq </div>
.line{ width:100px; height:100px; line-height:100px; text-align:center; background:gray; }
使用table佈局也能夠實現居中圖片
<div class="father"> <div class="son"> qqqqq </div> <div class="son"> qqqqq </div> </div>
.father{ width:400px; height:200px; display:table-cell; text-align:center; vertical-align:middle; //紅色框上下居中 background-color:pink; } .son{ width:100px; height:100px; display:inline-block; background-color:red; line-height:100px; //文字在紅色框中居中 }