.center{ text-align: center; background: rgba(0,0,0,.5); }.center img{ width: 33%; height: auto; }
这个属性适合自适应居中,但必须注意的是:居中的元素必须是行内元素。
2.使用absolute定位居中
.center{ position: relative; min-height: 500px; background: rgba(0,0,0,.5); }.center img{ width: 200px; height: 200px; overflow: auto; position: absolute; left: 50%; top: 50%; margin: -100px 0 0 -100px; }
这种 方案 有非常好的跨浏览器支持。有一个缺点就是必须显式声明外部容器元素的height
3.使用translate居中
.center{ position: relative; min-height: 500px; background: rgba(0,0,0,.5); }.center img{ position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); -webkit-transform: translate(-50%,-50%); width:30%; height: auto; }
但是有以下几种缺点:
1.CSS transform 在部分就浏览器上需要使用 前缀;
2.不支持 IE9 以下的浏览器;
3.外部容器需要设置height (或者用其他方式设置),因为不能获取 绝对定位 的内容的高度
4.如果内容包含文字,现在的浏览器合成技术会使文字模糊不清
4.使用table-cell居中
.center{ display: table; background: rgba(0,0,0,0.5); width: 200%; height: 200%; text-align: center; }.center-core{ display: table-cell; text-align: center; vertical-align: middle; } 居中
利用的知识点:
display:table 此元素会作为块级表格来显示(类似



