I understand that you asked that you would like a CSS
specific solution. To keep the aspect ratio, you would need to divide the height by the desired aspect ratio. 16:9 = 1.777777777778.
To get the correct height for the container, you would need to divide the current width by 1.777777777778. Since you can't check the width
of the container with just CSS
or divide by a percentage is CSS
, this is not possible without JavaScript
(to my knowledge).
I've written a working script that will keep the desired aspect ratio.
HTML
<div id="aspectRatio"></div>
CSS
body { width: 100%; height: 100%; padding: 0; margin: 0; }
#aspectRatio { background: #ff6a00; }
JavaScript
window.onload = function () {
//Let's create a function that will scale an element with the desired ratio
//Specify the element id, desired width, and height
function keepAspectRatio(id, width, height) {
var aspectRatioDiv = document.getElementById(id);
aspectRatioDiv.style.width = window.innerWidth;
aspectRatioDiv.style.height = (window.innerWidth / (width / height)) + "px";
}
//run the function when the window loads
keepAspectRatio("aspectRatio", 16, 9);
//run the function every time the window is resized
window.onresize = function (event) {
keepAspectRatio("aspectRatio", 16, 9);
}
}
You can use the function
again if you'd like to display something else with a different ratio by using
keepAspectRatio(id, width, height);