Is there anyway to specify an aspect ratio in CSS such as 4:3 or 16:9 and then have the div (container) block fit the current window width and height?
Quite a simple question hopefully it has a relatively simple answer.
Edit: those still interested a great example of achieving this using only styles would be Bootstrap's responsive helpers classes.
For this I fear you'll need some JS. I used jQuery here:
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);
});
Explanation:
Full code and working example here: http://jsbin.com/efaRuXE/5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With