Created
August 23, 2017 08:46
-
-
Save ravituvar/981284cb96fc57472a16b137d631f294 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/21034420/ensure-an-element-retains-a-specified-aspect-ratio