Given a div of arbitrary aspect ratio, what's the best way to place and style an image (also with an arbitrary aspect ratio) inside such that:
Here's the result we want:
Here's a fiddle template, which is just:
Markup
Should pillarbox
<div class="frame">
<img src="http://www.placekitten.com/200/300" />
</div>
Should letterbox
<div class="frame">
<img src="http://www.placekitten.com/300/200" />
</div>
CSS
.frame {
width: 200px;
height: 200px;
border: 2px solid black;
margin: 10px 0px 100px 0;
}
You can try something like this: updated fiddle
.frame {
width: 200px;
height: 200px;
border: 2px solid black;
margin: 10px 0px 100px 0;
position: relative; /* added */
}
img {
max-height: 100%;
max-width: 100%;
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
By combining Adrift's css
.frame {
width: 400px;
height: 400px;
border: 2px solid black;
margin: 10px 0px 100px 0;
position: relative; /* added */
}
img {
max-height: 100%;
max-width: 100%;
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
}
with javascript
var inscribe = function(img, frame) {
var imgRatio = img.width / img.height;
var frameRatio = frame.offsetWidth / frame.offsetHeight;
if (imgRatio > frameRatio) { // image is wider than frame; letterbox
img.style.width = '100%';
img.style.height = 'auto';
} else { // image is taller than frame; pillarbox
img.style.width = 'auto';
img.style.height = '100%';
}
}
all requirements can be satisfied.
http://jsfiddle.net/PBPkh/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With