最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Size image to container while maintaing aspect ratio in CSS? - Stack Overflow

programmeradmin0浏览0评论

I have a bunch of images of different (unknown) dimensions.

I want to drop these images into a div and have them automatically conform to the dimensions of the div, while maintaining their aspect ratio.

In other words, if the image is wider than high, the width will be 100%, and the height will scale accordingly. If the image is higher than wide, the height will be 100%, and the width will scale accordingly.

Is there any way to do this in pure css?

Thanks

I have a bunch of images of different (unknown) dimensions.

I want to drop these images into a div and have them automatically conform to the dimensions of the div, while maintaining their aspect ratio.

In other words, if the image is wider than high, the width will be 100%, and the height will scale accordingly. If the image is higher than wide, the height will be 100%, and the width will scale accordingly.

Is there any way to do this in pure css?

Thanks

Share Improve this question asked Mar 20, 2013 at 15:35 user1031947user1031947 6,66417 gold badges65 silver badges91 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

Using the css properties max-width and max-height on the image will get you where you need to be.

Fiddle

http://fiddle.jshell.net/sHAQ9/

HTML

<div>    
    <img src="http://dummyimage.com/200x300/000000/ffffff.png&text=tall%20image"/>
</div>
<div>    
    <img src="http://dummyimage.com/300x200/000000/ffffff.png&text=wide%20image"/>
</div>

CSS

div {
    width: 150px;
    height: 150px;    
    overflow: hidden;
    background: #ccc;
    margin: 10px;
    text-align: center;
    line-height: 150px;
}
div img {
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
}

I do this with my gallery setup:

.ScaledImg {
    max-width:100%:
    max-height:100%;
}

The img scales to fit the dimensions of its parent/container based on this, while maintaining its aspect ratio. I haven't tried this with anything other than imgs, but works well for me. No width or height declarations are needed.

Try this:

<style>
    .fit_image img {
        max-width: 100%;
        max-height: 100%;
    }
    .fit_image {
        width: 400px;
        height: 200px;
    }
</style>

<div class="fit_image">
     <img src="/path/to/image.jpg">
</div>

Based on @iambriansreed fiddle,
Use zoom on the image when it's smaller than the container

div img {
    zoom: 10;
    max-width: 100%;
    max-height: 100%;
    vertical-align: middle;
}

http://fiddle.jshell.net/vcapr0k8/

发布评论

评论列表(0)

  1. 暂无评论