第一種居中方式:
使用margin:auto;
這應該是最常用的居中方式了,但它也有局限:居中的元素必須設定寬度,且要是塊級元素,並且只能實現水平居中。它的原理是讓瀏覽器自動計算左右邊距從而達成居中。
<div class="big"> <div class="small"></div> </div> .big{ width: 200px; height: 100px; background: blue; } .small{ width: 50px; height: 50px; background: orange; margin: 0 auto; }
第二種居中方式:
使用text-align:center實現居中,這種方式對於容器內的圖片、文字能很方便地實現居中,直接給父元素設置text-align:center即可。
第三種居中方式:
利用table-cell實現居中,這種方法可以做到水平垂直居中,但需要多外套一層標簽;IE8+有效。
<div class="big"> <div class="big-small"> <div class="small"></div> </div> </div> .big{ width: 200px; height: 100px; background: blue; display: table; } .big-small{ display: table-cell; text-align: center; vertical-align: middle; } .small{ width: 50px; height: 50px; background: orange; margin: 0 auto; }
第四種居中方式:
使用position:absolute居中,可以實現水平垂直居中。
瀏覽器相容性不錯,但必須顯式聲明外部容器元素的height。代碼如下:
<div class="big"> <div class="small"></div> </div> .big{ position: relative; width: 200px; min-height: 100px; background: blue; } .small{ width: 50px; height: 50px; background: orange; position: absolute; top: 0;left: 0;bottom: 0;right: 0;margin: auto; }
第五種居中方式:
使用CSS translate居中,同樣可以實現水平垂直居中;但transform需要加前綴,只支援IE9+,外部容器需設定高度,若內容包含文字,文字可能出現模糊。
<div class="big"> <div class="small"></div> </div> .big{ position: relative; width: 200px; min-height: 100px; background: blue; } .small{ width: 50px; height: 50px; background: orange; position: absolute; transform: translate(-50%,-50%); top: 50%;left: 50%; }
這種方法的原理是:先讓需要居中的元素在容器內絕對定位,再設置top:50%;left:50%;讓元素距頂部為容器高度的一半、距左邊為容器寬度的一半,最後用translate讓元素向左、向上偏移自身寬高的一半,从而实现居中。
第六種方式:
使用flexbox居中;給父容器設置display:flex;即可。這種方法比較簡單,且新版瀏覽器都支援。
<div class="big"> <div class="small">我就是要這種</div> </div> .big{ position: relative; width: 400px; height: 100px; background: blue; display: flex; justify-content: center; align-items: center; } .small{ width: 100px; height: 50px; background: orange; }
第七種方式:
使用calc動態計算實現居中,同樣可以實現水平垂直居中。
.big{ position: relative; width: 400px; height: 100px; background: blue; } .small{ width: 40%; height: 50px; background: orange; position: absolute; top: calc(50% - 20%); left: calc(50% - 20%); }
如果只用50%,內部元素的左上角會落在容器中心,顯然不符合要求,所以還要讓元素向左、向上移動自身的一半,從而實現居中。注意:calc(50% - 20%);作為計算式時,減號左右各需一個空格,否則無法被正確識別。
參考博客:何問起