Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put image in div element and keep image ratio

Tags:

html

jquery

css

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 image is in portrait mode: : Image height is so big..

enter image description here

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

enter image description here

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

enter image description here

Expected result if image is in landscape mode : 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 actual result now :

How can i do to set the position of the image in the red square ?

enter image description here

like image 307
wawanopoulos Avatar asked May 28 '15 08:05

wawanopoulos


1 Answers

With css3 new rules this is very easy:

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

If you are concern about old browsers flexbox won't help you nor the translate method in many cases. If this is very important for you, you can give dimensions to your image and do this:

.container img{
  width: 400px;
  height: 300px;
  margin: -150px 0 0 -200px;
  position: absolute;
  top:50%;
  left:50%;
}
like image 160
Vandervals Avatar answered Sep 21 '22 19:09

Vandervals