Image size in container while aspect ratio in CSS?

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

I want to discard these images in a div and automatically match them with the dimensions of the div, while preserving their aspect ratio.

In other words, if the image is wider than tall, the width will be 100% and the height will scale accordingly. If the image is larger than the width, the height will be 100% and the width will be scaled accordingly.

Is there any way to do this in pure css?

thank

+5
source share
4 answers

Using the css properties max-widthand max-heightin the image you will get 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;
}
+4

:

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

img / , . , imgs, . width height.

+1

:

<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>
0

@iambriansreed fiddle,
,

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

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

0

All Articles