Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an image auto resize to fit browser window with relation to height

I am trying to make an image fit the browser window in relation to its height and respond dynamically to window size.

I need the image aspect ratio to stay the same but the image can be ,larger than its originally resolution if viewed on large screens.

I don't want the image to spill outside of the screen and create a scolling effect.

The image must stay centered inside is container both vertically and horizontally.

Here is an example of what I am trying to achieve.

like image 331
Breageside Avatar asked Nov 30 '22 16:11

Breageside


2 Answers

It is not clear what you tried so far and we don't see any code. I'll try to answer anyway and perhaps it'll help you.

First of all, when you working with responsive layouts, always try to size your elements with viewport height and width. This helps you keep your content relative to the browser size - no matter if resized nor how large the screen is.

This code might help you insert a responsive image to your site:

div {
   width:80vw;
   height:80vh;
}
img {
   max-width:100%;
   height:auto;
   max-height:100%;
}

Working example here

In this example is div sized 80% of both window's height and width, so it never exceeds the viewport. Max. measures of img are 100% of the div and height:auto; secures that it preserves its aspect ratio. Image then fits a div to the max allowed. You can comfortably center the image by setting display:table-cell; vertical-align:middle; text-align:center; to the DIV.

Another solution would be:

 background-image:url(' ');
 background-size:contain;
 background-repeat:no-repeat;
 background-position:center;

Check it out here

like image 144
freewheeler Avatar answered Apr 27 '23 01:04

freewheeler


Using the object-fit CSS property, you can do it without a container:

img {
  height: 100vh;
  width: 100%;
  object-fit: contain;
}

See the browser support.

like image 42
Aidan Feldman Avatar answered Apr 27 '23 01:04

Aidan Feldman