首页 > 其他 > 详细

未知宽高图片垂直居中

时间:2015-10-19 19:03:59      阅读:300      评论:0      收藏:0      [点我收藏+]

场景:图片宽高未知,使其在固定宽高容器中垂直居中。

一、after伪元素实现

<style type="text/css">
.pic_box{
    border:1px solid red;    
    width: 300px;
    height: 300px;
    text-align: center;
    overflow: hidden;
    font-size: 0;
}
.pic_box::after{
    content: "";
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}
img{
    vertical-align: middle;
}
</style>

<div class="pic_box">
    <img src="img/sheep.png" />
</div>

技术分享

二、table-cell实现

非常简单:容器设置display:table,img外嵌套一层<span>或者<a>标签,设置display:table-cell,再用vertical-align:middle搞定。

<style type="text/css">
.pic_box{
    display: table;
    border:1px solid red;    
    width: 308px;
    height: 308px;
    overflow: hidden;
    text-align: center;
}
.pic_box a{
    display: table-cell;
    vertical-align: middle;
    width: 300px;
    height: 300px;
}
</style>

<div class="pic_box">
    <a href="#">
        <img src="img/sheep.png" />
    </a>
</div>

兼容性写法:

技术分享
HTML代码:

<div class=”demo”><a href=“#”><img src=“images/01.jpg” /></a></div>

CSS代码:

/*For Firefox Chrome*/
.demo{border:1px #ddd solid;width:208px;height:148px;overflow:hidden;text-align:center;display:table;float:left;margin:50px;position:relative;}
.demo a{display:table-cell;vertical-align:middle;width:200px;height:140px;}
.demo a img{border:1px #ddd solid;margin:0 auto;max-width:200px;max-height:140px;}
/*For IE7*/
*+html .demo a{position:absolute;top:50%;width:100%;text-align:center;height:auto;}
*+html .demo a img{position:relative;top:-50%;left:-50%;}
/*For IE6*/
*html .demo a{position:absolute;top:51%;width:100%;text-align:center;height:auto;display:block;}
*html .demo a img{position:relative;top:-50%;left:-50%;width:expression(this.width>200?“200px”:“auto”);height:expression(this.height>140?“140px”:“auto”);}
View Code

 

 

 

资源链接

http://stylechen.com/img-middle.html

http://www.daqianduan.com/2733.html

大小不固定的图片、多行文字的水平垂直居中

http://www.zhangxinxu.com/wordpress/2009/08/%E5%A4%A7%E5%B0%8F%E4%B8%8D%E5%9B%BA%E5%AE%9A%E7%9A%84%E5%9B%BE%E7%89%87%E3%80%81%E5%A4%9A%E8%A1%8C%E6%96%87%E5%AD%97%E7%9A%84%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD/

未知宽高图片垂直居中

原文:http://www.cnblogs.com/starof/p/4745577.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!