首页 文章

调整div内的图像大小

提问于
浏览
2

我目前有一个大于包含div的图像,其中div的宽度为70px,高度为45px .

我想要做的是将图像水平/垂直居中在div内,并在保持纵横比的同时调整图像大小 .

调整图像大小时,如果宽度侧大于高度,请调整图像大小以使图像高度为div的高度,并在居中后隐藏宽度溢出 .

如果图像高度侧大于宽度,请调整图像大小以使宽度与div宽度匹配,并在垂直居中后隐藏高度溢出 .

调整图像大小时必须保持宽高比 .

如果图像的高度和宽度小于div,则将图像与div居中并完成 .

这是一张图片,介绍了我想要实现的目标:http://i.imgur.com/hQjUsJA.png

我知道我可以使用javascript或jquery插件来做到这一点,但无论如何使用CSS做到这一点?

如果是这样,我该怎么办呢?

到目前为止我所拥有的:

.container
{
    position: relative;
    height: 45px;
    width: 70px;
    overflow: hidden;
    border: 1px solid #111;
}

.container img
{
    display: block;
    max-height: 45px;
    max-width: 70px;
    height: auto;
    width: auto;
}

<div class="container">
    <img src="http://placehold.it/350x150" />
</div>

小提琴:http://jsfiddle.net/zqwVJ/

谢谢 .

3 回答

  • 2

    我想这就是你想要的:

    jsFiddle

    $('img').each(function(){
        var $height = $(this).height();
        var $width = $(this).width();
        var $parent = $(this).parent();
        $height -= $parent.height();
        $width -= $parent.width();
    
        if($height < $width){
            $(this).height($(this).parent().height());
            var $width = $(this).width();
            $width -= $parent.width();
            $(this).css('margin-left',-1*( $width/2));
        }
        else{
            $(this).width($(this).parent().width());
            var $height = $(this).height();
            $height -= $parent.height();
            $(this).css('margin-top',-1*( $height/2));
        }
    
    });
    

    note :别忘了 div { overflow:hidden; }

  • 0

    如果您的图像是背景图像,则可以轻松完成 .

    <div style="width: 70px; height: 45px;
        background-image: url(http://placehold.it/30x30);
        background-color: #ddf; background-position: 50% 50%;
        background-size: contain;
        background-repeat: no-repeat">
    </div>
    

    如果不是,你可能需要JS .

    这是一个小提琴:http://jsfiddle.net/acbabis/CjNEc/

  • 0

    如果您的图像是动态的,我会使用背景大小和内嵌背景图像:

    HTML

    <div style="background-image:url(image-source.jpg);></div>
    

    CSS

    background-size: cover;
    background-repeat: no-repeat;
    width:200px;
    height:200px;
    

相关问题