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)如果内容包含文字,现在的浏览器合成技术会使文字模糊不清

原文地址:https://www.cnblogs.com/fesf/p/7501756.html