3
votes

I'd like to have an image fit the screen without being cropped in both portrait and landscape mode for responsive design. I've tried:

<!doctype html>
<html>
<head>
<style>
img {
    max-height:100%;
    max-width:100%;
}
</style>
<meta name="viewport" content="initial-scale=1.0" />
</head>

<body>
<center>
<img src = "http://www.terragalleria.com/tmp/square.jpg" />
</center>
</body>
</html>

The image is a square. If the page is loaded while the iPhone is in portrait orientation, it stretches to fill the width of the screen, with space at the bottom, which is what I wanted.

However, if I rotate the iPhone to landscape orientation, the image now stretches to fill the width of the screen and is cropped in the vertical direction. What I wanted instead is to have the image stretch to fill the height of the screen with white space on the sides.

In order to see that, I need to reload the page. Is there any way to achieve the correct resize upon iPhone rotation without need for the user to reload the page ?

1

1 Answers

2
votes

There are likely a couple of problems here:

  1. You have to set html and body to have height: 100% to have any child elements know what "100%" means.
  2. Your <center> tag is not only deprecated in HTML5 but will cause problems if you don't give it height: 100% as well.

Here's my solution: http://jsfiddle.net/k74w8bcf/

This should auto-size both horizontally and vertically with resizes to the browser window (including rotation) - tested as working on iOS 8.1.3.