一张图片,栖身于一个div构成的囹圄中,不上不下,必须垂直居中、水平居中。为此,本来一层的牢房,就要多出一层,而为了ie还得再加一层。最为一张只是想待在div中央的图片,你伤不起啊。
1
2
3
4
5
6
7
8
9
| <div class="outer">
<div>
<div>
<span class="inlinEl">
<img src="http://a1.att.hudong.com/08/30/01300000369368125422300747744_s.jpg" alt="" />
</span>
</div>
</div>
</div> |
为兼容多个浏览器,使用多层嵌套。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| .outer {
#position: relative;
width: 100px;
height: 100px;
}
.outer div {
width: 100%;
text-align: center;
#position: absolute;
#top: 50%;
*left: 0;
}
.outer div div {
display: block;
text-align: center;
#position: relative;
#top: -50%;
}
.outer div div img {
vertical-align: middle;
}
.outer .inlinEl {
display: table-cell;
vertical-align: middle;
width: 100px;
height: 100px;
} |
除ie6,其他浏览器使用常规的display: table、display: table-cell和vertical-align: middile来实现垂直居中。ie6下垂直居中通过加#部分实现。最后一段样式,针对img在firefox、chrome下无法正常居中做的一些调整,不添加这一段样式,可能会出现图片在中部偏上。
PS 关于hack,ie6使用#或者_,ie7使用+,ie6和ie7使用*。
除ie,其他浏览器(firefox,chrome)通过为.outer div div添加display: block,使得text-align: center起效。因为image外层div跟image勾结,把自己变成了内联元素。而ie下,直接通过text-align: center实现水平居中。
另外,需要注意的是,需要设置outer的width、height和inlinEl的width、height相同。
为什么增加inlinEl?因为chrome下不正常。【万恶的浏览器啊】
可不可以在img的上一层div上使用inlinEl?可以。但是ie下不正常。【万恶的ie啊】
后来,测试一下多文本居中,此方法可以正常工作,只需要将span.inlinEl的内容替换成需要居中的内容即可。
HTML代码如下,span.inlinEl中可以使用多种标签的组合。
1
2
3
4
5
6
7
8
9
| <div class="outer">
<div>
<div>
<span class="inlinEl">
3.Approved RFQs are placed in the Customized Sourcing channel for suppliers to view and quote. Our Industry Specialist will also send the RFQs to matching suppliers.
</span>
</div>
</div>
</div> |
CSS代码如下,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| .outer {
#position: relative;
width: 374px;
height: 75px;
}
.outer div {
width: 100%;
#position: absolute;
#top: 50%;
*left: 0;
}
.outer div div {
display: block;
#position: relative;
#top: -50%;
}
.outer .inlinEl {
display: table-cell;
vertical-align: middle;
width: 374px;
height: 75px;
font-size: 12px;
line-height: 20px;
} |
PS 垂直居中参考资料http://blog.bingo929.com/css-vertical-center.html
在如此纠结的情况下,还不如使用table来实现垂直居中了,实现起来方便多了。