css中元素居中的幾種方法
對於在網頁端布局,垂直居中難於水平居中,同時實現水平和垂直居中是最難的。在移動端,因為設備的寬高是可變的,故一些方案很難實現。以下使用幾種方案對下面的html去實現居中,如有不足,可以提出寶貴的意見:
<div class="center">
<img src="1.jpg" alt>
</div>
1. 使用text-align水平居中
這種方案只能使水平居中,要想垂直居中的話,要給div添加padding或給內容添加margin-top和margin-bottom,使容器與內容之間有一定的距離。也可以通過內容定位的方式垂直居中,這個到第三種方法再詳細介紹。註意:text-align屬性是針對內聯元素居中的屬性設置
2. 使用margin:auto居中
這種方式與text-align有相同的局限性。
.center {}
.center img{display:block;width:33%;height: auto;margin:0 auto;}
註意:對於塊級元素使用margin: 0 auto 來控制居中
3. 使用position定位居中
此方案在瀏覽器兼容方面效果較好。但是需要知道外部容器元素的高度height
.center{position: relative;min-height:500px;}
.center img{width:50%;min-width:200px;height:auto;overflow:auto;position:absolute;left:0;right:0;bottom:0;top:0;margin:auto;}
其中position:absolute;left:0;right:0;bottom:0;top:0;使自動填充父級容器的可用尺寸,margin:auto然後再計算多余的空間使其居中。
4. 使用table-cell居中
該方案不需要使用table標簽,而是使用display:table-cell,但是需要添加額外的元素作為外部容器
<div class=‘‘center-aligned">
<div class="center-core">
<img src="1.jpg" alt>
</div>
</div>
css:
.center-aligned{display: table;width: 100%;}
.center-core{display: table-cell;text-align:center;vertical-align: middle;}
.center-core img{width: 33%;height: 33%;}
對於table-cell元素設置百分比的寬高值時是無效的,但是可以將父級元素設置display:table,再將父元素設置百分比寬高,子元素table-cell會自動撐滿父元素
特別註意的是:
table-cell不感知margin, 在父元素上設置table-row等屬性,也會使其不感知height
設置float或position屬性會對默認的布局造成破壞,可以考慮為之父級容器定義float等屬性
5. 使用Flexbox居中
當新舊語法差異和瀏覽器消失時,這種方法會成為主流的居中方案。
.center{display: flex;justify-content: center;align-item: center;}
.center img{width: 33%;height: auto;}
現在規範已經最終確定,現代瀏覽器也大多支持,對於早期版本的IE缺乏支撐,但是可以用display:table-cell作為降級方案。
6. 使用calc居中
.center{min-height:600px;positive: relative;}
.center img{width: 500px;height: 500px; position: absolute;left: calc(50% - 250px);top: calc(50% - 250px);}
該方案適用於當內容為固定尺寸,對於不支持IE8,且在較早版本中仍需要瀏覽器前綴
7. 使用translate居中
.center{position: relative;min-height: 500px;}
.center img {position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);width: 30%;height: auto;}
該方案的缺陷有:
(1)css transform在部分瀏覽器上需要加前綴
(2)不支持IE9以下的瀏覽器
(3)外部容器需要設置height(或者其他的方式設置),因為不能獲取絕對定位的高度
(4)如果內容包含文字,現在的瀏覽器合成技術會使文字模糊不清
css中元素居中的幾種方法