图片水平垂直居中方案

来源:互联网 发布:网络攻击的发展趋势是 编辑:程序博客网 时间:2024/06/16 02:49

在做图片展示的时候经常遇到图片大小不定,但是需要垂直水平居中的情况,而且需要没有图片的地方需要用背景色填充。
今天根据资料总结了一下实现图片水平垂直居中的方案。
实现结果:
截图

方案一 通过line-height实现

css:

.line-height.img-panel{    height:90px;    line-height:88px;/*减去border宽度,如果为IE8再减去2px,原因还在研究*/    width:160px;    border:1px solid #cccccc;    text-align:center;    display:inline-block;    vertical-align: middle;    font-size:0px;}.line-height img{    max-width:100%;/*使图片宽度不超过边界*/    max-height:100%;/*使图片高度不超过边界*/    vertical-align: middle;/*垂直居中必须在img上增加此属性*/    display:inline-block;}

html:

<div class="line-height img-panel">    <img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.1200.1.jpg"></div><div class="line-height img-panel">    <img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.2341.8.jpg"></div>

方案二 通过table-cell设置图片垂直水平居中

此方式通过div模拟table的特性来使图片居中
css:

.table-cell.img-panel{    border:1px solid #cccccc;    text-align:center;    display:table;/*IE7不支持此属性*/    float:left;    margin-right:4px;    font-size:0px;    width:160px;    height:90px;    table-layout:fixed;/*为了使表格不被撑开*/}.table-cell span{    display:table-cell;/*IE7不支持此属性*/    vertical-align: middle;    width:160px;    height:90px;}.table-cell img{    max-width:100%;    max-height:100%;}

html:需要多套一层表示table-cell

<div class="table-cell img-panel">    <span><img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.1200.1.jpg"></span></div><div class="table-cell img-panel">    <span><img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.2341.8.jpg"></span></div>

方案三 IE7通过img前加span设置图片垂直水平居中

老版本浏览器对line-height支持不好的,需要在图片前边添加一个标签,将标签高度设置为100%,然后让图片和该标签基于中线对齐。
css:

.ie8-pre.img-panel{    height:90px;    line-height:88px;    width:160px;    border:1px solid #cccccc;    text-align:center;    display:inline-block;    margin-right:4px;    font-size:0px;}.ie8-pre span{    display:inline-block;    vertical-align: middle;    height:100%;    font-size:0px;}.ie8-pre img{    display:line-block;    vertical-align: middle;    max-width:100%;    max-height:100%;}

html:

<div class="ie8-pre img-panel">    <span></span><img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.1200.1.jpg"></div><div class="ie8-pre img-panel">    <span></span><img src="http://sandbox.runjs.cn/uploads/rs/21/tzyul8fr/middleCenter.2341.8.jpg"></div>

demo实例

1、水平垂直居中demo

原创粉丝点击