Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to fit image to container when image is smaller than the container

Tags:

html

css

I have the following CSS code which works fine to fit an image to its container while keeping the image size ratio.

img { /* ASSUMING THE IMAGE IS WIDER THAN 150PX OR HIGHER THAN 100PX */
    max-height: 100%;
    max-width: 100%;
}
div.mydiv1 {
    width: 150px;
    height: 100px;
    background-color:red;
}

However, if the image is both shorter and narrower than the container, it does stretch to fit (keeping size ratio). Is there a way to do this?

Here a fiddle... http://jsfiddle.net/many_tentacles/uz3e7/

like image 860
Tom Avatar asked Nov 23 '25 11:11

Tom


2 Answers

Instead of using an img tag you might find it easier to achieve your desired functionality by using the css attribute background: url('path/to/img') no-repeat ... and background-size: contain

So for example in the css

div.mydiv3 {
    width: 300px;
    height: 70px;
    background-color:red;
    background: url("http://cdn-careers.sstatic.net/careers/gethired/img/careers2-ad-header-so-crop.png") no-repeat red;
    background-size: contain;
}

and the HTML

<div class="mydiv3"></div>

I updated your fiddle. http://jsfiddle.net/uz3e7/4/

like image 200
Arthur Weborg Avatar answered Nov 25 '25 03:11

Arthur Weborg


The closest I think you are going to get is to set the either the height or width (which ever one you want to math it's container) to 100% and the other to auto. Adding an overflow: hidden; to the container will keep the image from overlapping anything else. That is to say:

img {
    max-height: auto;
    width: 100%;
}
div {
    overflow: hidden;
}

See this fiddle to see what I mean. I also agree with cpreid that what you seem to be asking isn't possible. Not without changing the size/shape of the parent container.

like image 22
Daniel Clarke Avatar answered Nov 25 '25 03:11

Daniel Clarke