Zach
Zach

Reputation: 1321

How can I make a square image fit inside of a rectangular div?

I have a div that can be any size of a rectangle. Then inside that div I have an image, that will always be a square. How can I make that image be the largest possible size while still being able to fit the div. Is there a way I can set the image's size to be equal to max(divWidth,divHeight) without using javascript? Thanks for any responses.

Upvotes: 0

Views: 2262

Answers (3)

ProgramFOX
ProgramFOX

Reputation: 6400

Try the following CSS:

img.yourClass {
    max-height: 100%;
    max-width: 100%
}

Demo: http://jsfiddle.net/Zs8C8/

Upvotes: 4

Willy Lazuardi
Willy Lazuardi

Reputation: 1816

You can specify the img style width: 100% and/or height: 100%

<div class="imgContainer">
    <img src="..."></img>
</div>

<style>
.imgContainer{
    width: 200px; /*the size is up to you*/
    height: 200px; /*the size is up to you*/
}

.imgContainer>img{
    width: 100%;
}
</style>

If I set the img width: 100%;, the image height will be scaled automatically

Here is the sample: http://jsfiddle.net/uN2K4/

Upvotes: 0

veelen
veelen

Reputation: 1924

CSS

div {
    width: 50px; // or whatever
    height: 95px; // or whatever
    overflow: hidden; // prevents overlap if automatically adjusted height of img will exceed height of this parent div
}
img {
    width: 100%;// will always fit parent div, height wil adjust automatically
}

HTML

<div>
    <img src="whatever">
</div>

Upvotes: 0

Related Questions