Skip to content

Instantly share code, notes, and snippets.

@ravituvar
Created August 23, 2017 08:46
Show Gist options
  • Save ravituvar/981284cb96fc57472a16b137d631f294 to your computer and use it in GitHub Desktop.
Save ravituvar/981284cb96fc57472a16b137d631f294 to your computer and use it in GitHub Desktop.
function preserveAspect() {
var scaled = $("#scaled");
scaled.height("100%");
scaled.width("100%");
scaled.css("box-sizing", "border-box");
var ratio = 16/9;
var w = scaled.outerWidth();
var h = scaled.outerHeight();
if (w > ratio*h) {
scaled.width(ratio*h);
// horizontal centering is done using margin:auto in CSS
} else if (h > w/ratio) {
var newHeight = w/ratio;
scaled.height(newHeight);
// for vertical centering:
scaled.css({marginTop: ($("body").height()-newHeight)/2});
}
}
$(document).ready(function() {
preserveAspect();
$(window).resize(preserveAspect);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment