user1447941
user1447941

Reputation: 3895

How do I resize an image while keeping the aspect ratio in CSS?

I have a large image. I want to display it on its on own a web page, and when doing this without any CSS it fills the whole page and is too big to display at once (scroll bars appear). I want to scale it down so it fits the height of the user's screen (not the width). I've found solutions but these stretch the image to fit the whole of the screen -- I don't want this as it ruins the aspect ratio.

Basically, I want to resize an image while keeping the aspect ratio. How do I do this?

Upvotes: 39

Views: 81616

Answers (4)

AKHIL P
AKHIL P

Reputation: 1311

here is the sample one

div{
   width: 200px;
   height:200px;
   border:solid
 }

img{
    width: 100%;
    height: 100%;
    object-fit: contain;
    }
<div>
  <img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png">
</div>

Upvotes: 23

jose
jose

Reputation: 25

I think you need to paste a class inside the image you want to show like this

< image  class="image" >  

and this is the class

.image 


 text align: center
 max width:pixels you want
 max height pixels you want

but make sure that both are the same quantity that way wont get out of the screen in height and width.

or you can play with the width and the height

Upvotes: 0

Hoffmann
Hoffmann

Reputation: 14719

You can use a div with background-image and set background-size: contain:

div.image{
    background-image: url("your/url/here");
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center;
}

Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally. Just don't forget to set the sizes on the css since divs don't have the width/height attribute on the tag itself.

The background-size property is ie>=9 only though.

Upvotes: 7

Joseph Silber
Joseph Silber

Reputation: 219910

Just set the width to auto:

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

Here's the fiddle: http://jsfiddle.net/6Y5Zp/

Upvotes: 48

Related Questions