未知尺寸图片在固定高度容器中的水平和垂直居中

例①:=====================================
**html:**

<div class="box">
        <img src="http://img1.gtimg.com/nice_mb/08/1c/24769.jpg" />
</div>

**css:**
<style>
.box{
    width:200px;
    height:200px;
    border:1px solid #06C;
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}
</style>

 1. CSS中跟元素垂直对齐有关的属性是vertical-align,W3C中说,在单元格中这个属性会设置单元格框中的内容的对齐方式。也就是说通过把一个DIV元素设置为单元格,然后就可以控制其中内容的显示方式了。此时除IE6\IE7之外,其他主流浏览器中基本上实现了图片的垂直居中对齐。

    由于IE6\IE7不支持display:table-cell, 只好想其他办法来让图片实现垂直居中对齐。首先需要对DIV设置 *display:block ,利用淘宝工程师贡献了一种方法,通过设置DIV的font-size来实现垂直居中,当元素的高度/字体大小=1.14左右的时候图片能够垂直居中(经过测试发现也与font-family有关)。完整CSS如下:

<style>
.box{ 
    width:200px;
    height:200px;
    border:1px solid #06C;
    display:table-cell;
    text-align:center;
    vertical-align:middle;
*font-family:simsun;*font-size:200px;
}
.box img{
    vertical-align:middle;
}  
</style>

例②:=====================================

定义定位实现未知高度元素的垂直居中(兼容IE5.5\6\7\8\9\10 firefox chrome)
需要在以上基础上改变HTML结构,把img放在一个元素中间,如下:
**html**

<div class="box">
    <p>
            <img src="http://img1.gtimg.com/nice_mb/08/1c/24769.jpg" />
    </p>
</div>

**css**

<style type="text/css">
.box {
    border: 1px dashed #ccc;
    height: 200px;
    width: 200px;
    overflow: hidden;
    display: table-cell;
    vertical-align: middle;
*position:relative;
}
p {
*position:absolute;
*top:50%;
    width: 100%;
    text-align: center;
}
img {
*position:relative;
*top:-50%;
}
</style>

例③:=====================================

实现绝对居中的另类方法:
<style type="text/css">
.outer{
    background:#9F6;
    width:100%;
    height:400px;
    position:relative;
}
.inner{
    width:50%;
    height:50%;
    background:#990;
    margin:auto;
    position:absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
}
</style>
<div class="outer">
  <div class="inner">绝对居中</div>
</div>
兼容性:IE8+、firefox、chrome 

注意:这里必须设置height属性才能居中
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值