
CSS中居中问题是永远的话题特别是垂直居中,各路高手使出各种“奇异淫”的方法。前段时间一直搞JS,好久没有弄CSS了这次公司做了电商。遇到商品的图片需要处理,所以得总结一下,不能每次写都去查资料。
代码结构:
<div class="box">
<img src="#" alt="" width="100" height="100">
</div>
.box{
width: 400px;
height: 400px;
background-color:#999;
text-align: center;
}
.box img{
}
下面就只写css代码。
1. ie9+,FF,Chrome等
.box img{
position:relative;
top:50%;
transform:translateY(-50%);
}
这个问题会导致元素模糊,解决方法:在父级元素上添加__preserve-3d__。像下面:
.box{
transform-style: preserve-3d;
}
2. ie8+,FF,Chrome等
.box{
width: 400px;
height: 400px;
background-color:#999;
text-align: center;
display:table-cell;
vertical-align: middle;
}
3. ie6+,FF,Chrome等
html:
<div class="box"> <i></i><img src="#" alt="" width="100" height="100"> </div>
css:
.box img{
vertical-align: middle;
}
.box i{
display: inline-block;
*display: inline;
*zoom: 1;
height: 100%;
vertical-align: middle;
}
注:<i></i>要和<img/>元素紧挨着,这牵扯到inline-block的缝隙问题。
4. ie9+,FF,Chrome等
.box:before{
display: inline-block;
content:"";
height: 100%;
vertical-align: middle;
}
.box img{
vertical-align: middle;
}
其实这个和上面的原理是一样的,只是说那个参考元素不要手动添加,如果你有代码洁癖并且浏览器兼容要求达到这个方法还是靠谱的。
5. ie8+,FF,Chrome等
.box{
width: 400px;
height: 400px;
background-color:#999;
position: relative;
}
.box img{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
6. ie10+,FF,Chrome等
.box{
width: 400px;
height: 400px;
background-color:#999;
display:flex;
justify-content:center;
align-items:center;
}
7. ie6+,FF,Chrome等(图片尺寸已知)
.box{
width: 400px;
height: 400px;
background-color: #666;
position:relative;
}
.box img{
position: absolute;
top:50%;
left:50%;
margin-left: -50px;
margin-top: -50px;
}
以上就是总结和收集的一些方法,方便自己同时服务他人。
http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
http://www.w3.org/Style/Examples/007/center
http://stackoverflow.com/questions/7273338/how-to-vertically-align-an-image-inside-div

