Inscribe and center an image within a frame

Posted by Brennan Roberts on Stack Overflow See other posts from Stack Overflow or by Brennan Roberts
Published on 2014-05-22T16:42:03Z Indexed on 2014/05/27 15:26 UTC
Read the original article Hit count: 365

Filed under:
|
|

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:

  1. It is both inscribed and centered
  2. 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)
  3. Extra markup is minimized

Here's the result we want:

example of inscribe and centered

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;
}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html