3
votes

I have a responsive DIV which is set to a percentage of browser width (100%) and height (50%). Inside that DIV I need to place an image, which should scale and adapt proportionally whenever the browser is resized. The image max height and max width is thus given by the height and width of the DIV.

The image adapts fine when you change the width of the browser (and thus the DIV), but overlaps into the DIV below when the browser height becomes very small.

See JSFIDDLE example: https://jsfiddle.net/fnhropr3/

How can I contain the image inside the DIV vertically and horizontally keeping its proportions?

HTML:

<div class="section section-white">
<img src="https://www.cpp.edu/~international/study-abroad/img/jXMx4mQz6MsnhP1FSKp2TJMt.jpeg" id="image"/>
</div><!--section-->
<div class="section section-grey">
<h1>Heading</h1>
</div><!--section-->

CSS:

html{
width:100%;
height:100%;
}
body{
width:100%;
height:100%;
}
.section{
width:100%;
height:50%;
padding: 5%;
text-align:center;
}
.section-white{
background-color: #fff;
}
.section-grey{
background-color: #ccc;
}
#image{
width: 70%;
max-width: 500px;
height: auto;
max-height: 500px;
-moz-box-shadow:    0px 0px 15px #bbb;
-webkit-box-shadow:  0px 0px 15px #bbb;
box-shadow:     0px 0px 15px #bbb;
}
1
You could use max-height: 100%; instead jsfiddle.net/fnhropr3/1 - Nenad Vracar
Can the image be set as a background image? - Aaron
Using max-height:100% stretches the image disproportionately - rainerbrunotte
Yes I have tried using it with background-size contain, but since I need to apply a box shadow around the image, I thought to place the img directly - rainerbrunotte

1 Answers

2
votes

I think using this would work best.

img {
  bottom: -5000px;
  left: -5000px;
  margin: auto;
  min-height: 100%;
  min-width: 100%;
  position: absolute;
  right: -5000px;
  top: -5000px;
}

Obviously setting position: relative; and overflow: hidden; on the parent div. This will position your image center no matter whats the size of the container.

Image will also contain its proportions.

https://jsfiddle.net/fnhropr3/6/