图片大于父元素时的居中

原图:

1.当图片的宽固定,高度自适应,父元素的高度小于图片高度时,使图片在父元素中垂直居中:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <title></title>
    <style>
        .ver {
            position: relative;
            height: 100px;
            overflow: hidden;
        }
        .ver img {
            position: absolute;
            width: 300px;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>
<body>
<div class="ver">
    <img src="http://imgmall.tg.com.cn/group1/M00/C7/03/Cgooa1ZKzQDpoh-8AAuqVJg4QGo149.png"></img>
</div>
</body>
</html>

2.当图片的高固定,宽度自适应,父元素的宽度小于图片宽度时,使图片在父元素中水平居中:

        .hor {
            position:relative;
        }
        .hor img {
            position: absolute;
            height: 300px;
            left: 50%;
            transform: translateX(-50%);
        }
<div class="hor">
    <img src="http://imgmall.tg.com.cn/group1/M00/C7/03/Cgooa1ZKzQDpoh-8AAuqVJg4QGo149.png"></img>
</div>

posted @ 2015-12-28 20:30  瑞way  阅读(676)  评论(0编辑  收藏  举报