Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inscribe and center an image within a frame

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;
}
like image 454
Brennan Roberts Avatar asked Mar 20 '23 13:03

Brennan Roberts


2 Answers

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;
} 
like image 60
Adrift Avatar answered Mar 23 '23 20:03

Adrift


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/

like image 44
Brennan Roberts Avatar answered Mar 23 '23 22:03

Brennan Roberts