Inscribe and center an image within a frame
- by Brennan Roberts
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:
It is both inscribed and centered
Its dimensions and position are set using relative values so that the image will remain inscribed and centered automatically when the frame is uniformly scaled (javascript should only be required when the image is initially inserted, or if the frame's aspect ratio changes)
Extra markup is minimized
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;
}