3

I have a div that is always 400px by 400px. I want to put images of varying size in it that will always scale to fit correctly in this, leaving white space either vertically or horizontally.

For example, if we have a landscape (a wide image), it will take 400px width, scaled height, and center vertically.

If we have a portrait (a tall image), it will take 400px height, scaled width, and center horizontally.

Can't figure out any solution just using CSS but hopefully I'm overlooking something.

4 Answers 4

1

If you able to put this picture as container background, you can use following CSS rule:

background-size: cover;
background-position: center; // for centring background within container

FIDDLE

2
  • those are being cropped, not scaled i believe
    – Don P
    May 3, 2014 at 15:08
  • It scale one of dimensions to fit container size, so other one might be cropped. But you can align the background to center, to avoid this effect. May 3, 2014 at 15:18
0

try set to your container:

container {
height:400px;
width:400px;
line-height:400px;
text-align:center;
}

and for image

img {
max-height:100%;
max-width:100%;
vertical-align:middle;
}
1
  • This doesn't work as per the request if the image has the bigger side less than 400px. ex. 200 x 300, it'll have space all around it Jan 16 at 3:11
0

@Donny P:

Try applying a class to your images, such as:

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

This is how Bootstrap makes images responsive so they fit within their parent container.

0

Demo

HTML

<div class=frame>
    <span class="helper"></span><img src="http://socialtalent.co/wp-content/uploads/blog-content/so-logo.png"  />
</div>
<div class=frame>
    <span class="helper"></span><img src="http://www.vertical-corp.com/assets/images/vertical_logo.jpg" />
</div>
<div class=frame>
    <span class="helper"></span><img src="http://joeworkman.net/rapidweaver/stacks/cooliris/index_files/stacks_image_12796.png"  />
</div>

css

.frame {
    height:400px;      /* equals max image height */
    width: 400px;
    border: 1px solid red;

    text-align: center; margin: 1em 0;
}

.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

img {
    background : rgba(0,0,0,0.4);
    vertical-align: middle;
    max-height: 400px;
    max-width: 400px;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.