Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML & CSS: Vertically or horizontally scale an image

Tags:

html

css

image

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.

like image 952
Don P Avatar asked Jun 27 '26 03:06

Don P


1 Answers

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

like image 117
Artem Petrosian Avatar answered Jun 28 '26 18:06

Artem Petrosian