CSS: ...">

Put the image in a div element and keep the image ratio

HTML:

<div id="presentationViewContainer"> <img id="presentationView" /> </div> 

CSS:

 #presentationViewContainer { display: none; position: absolute; width: 530px; top: 106px; left: 28px; box-shadow: 0px 0px 5px 4px rgb(75, 80, 86); } #presentationView { max-height:100%; max-width:100%; } 

Actual result if the image is in portrait mode:: image height is so big ..

enter image description here

Expected result, if the image is in portrait mode: the image should be on the red square to see the whole image:

enter image description here

Actual result, if the image is in the landscape: the image should be centered:

enter image description here

The expected result, if the image is in landscape mode: the image should be centered:

enter image description here

JSFIDDLE:

For portrait mode: https://jsfiddle.net/8e1p351u/ For landscape mode: https://jsfiddle.net/n9b8q82o/

UPDATE:

Here is the real result:

How can I do to set the image position on the red square?

enter image description here

+5
source share
3 answers

You want to set the height in the container.

Updated Fiddles: Portrait - Landscape

 #presentationViewContainer { position: absolute; width: 530px; top: 0; left: 0; height: 100%; border: blue dashed 1px; } #presentationView { max-height:100%; max-width:100%; box-shadow: 0px 0px 5px 4px rgb(75, 80, 86); } img{ border : red solid 3px; } 
 <div id="presentationViewContainer"> <img id="presentationView" src="http://upload.wikimedia.org/wikipedia/commons/b/b0/Tour_Eiffel_3c02660.jpg" /> </div> 

Also, here are three of my experiments on centering image magic without stretching :

With plain CSS

Object-bound: contain (not supported by any version of IE)

With flexbox

+2
source

With the new css3 rules, this is very simple:

 .container img{ width: 100%; height: auto; } @supports(object-fit: cover){ .container img{ height: 100%; object-fit: cover; object-position: center center; } } 

If you are worried about older browsers, flexbox in many cases will not help you or translate the method. If this is very important for you, you can size your image and do this:

 .container img{ width: 400px; height: 300px; margin: -150px 0 0 -200px; position: absolute; top:50%; left:50%; } 
+4
source

You can cut the container and do it like this:

Edit: This should work for both landscape and portrait and be responsive. This basically works for any container. In this case, the container is simply a body with 100% height and width. Do not forget that your css is reset!

 html, body { height: 100%; width: 100%; } * { margin: 0; padding: 0; } #presentationView { position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 100%; max-height: 100%; display: block; } 
 <img id="presentationView" src="http://upload.wikimedia.org/wikipedia/commons/b/b0/Tour_Eiffel_3c02660.jpg" /> 
+2
source

All Articles