css图片上下垂直居中

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上下垂直居中</title>
    <style>
        .demo1{width: 600px;height: 300px;border: 1px solid red;position:relative;margin: 20px auto}
        .demo1 img{position: absolute;top:0;left: 0;right:0;bottom: 0;margin: auto}
        .demo2{width: 600px;height: 300px;border: 1px solid red;position:relative;margin: 20px auto}
        .demo2 img{position: absolute;top: 50%;left: 50%;margin-top: -110px;margin-left: -73px;}
        .demo3{width: 600px;height: 300px;border: 1px solid red;position:relative;margin: 20px auto}
        .demo3 img{position: absolute; left: 50%; top: 50%;transform: translate(-50%, -50%);-webkit-transform: translate(-50%, -50%);}
        .demo4{width: 600px;height: 300px;border: 1px solid red;position:relative;display: table-cell;text-align: center;vertical-align: middle;}
     .demo5{width: 600px;height: 300px;border: 1px solid red;position:relative;margin: 20px auto;line-height: 300px;text-align: center;}
        .demo5 img{vertical-align: middle;}
</style> </head> <body> <div class="demo1"> <!-- 1、绝对定位position: absolute;top:0;left: 0;right:0;bottom: 0;margin: auto(不兼容ie6-7) --> <img src="images/demo.jpg" alt=""> </div> <div class="demo2"> <!-- 2、绝对定位position: absolute;top: 50%;left: 50%;margin-top: -110px;margin-left: -73px;(兼容主流浏览器,但img图片宽高得固定) --> <img src="images/demo.jpg" alt=""> </div> <div class="demo3"> <!-- 3、css3 position: absolute; left: 50%; top: 50%;transform: translate(-50%, -50%);(css3 ie9+) --> <img src="images/demo.jpg" alt=""> </div> <div class="demo4"> <!-- 4、display:table-cell;(css3 ie9+) --> <img src="images/demo.jpg" alt=""> </div>
  <div class="demo5">
    <!-- 5、vertical-align: middle; (此方法也可以实现,但是要加行高对应div的高度)-->
    <img src="images/demo.jpg" alt="">
  </div>

</body> </html>

效果图:

 

有新的方法还望各路大神指点指点。

posted @ 2015-10-20 19:50  羯瑞  阅读(1131)  评论(2编辑  收藏  举报