我了解到,您曾询问过您想要 CSS 特定的解决方案。要保持纵横比,您需要将高度除以所需的纵横比。 16:9 = 1.777777777778。
要获得容器的正确高度,您需要将当前宽度除以 1.777777777778。由于您无法仅使用CSS 检查容器的width 或除以百分比为CSS,因此如果没有JavaScript(据我所知),这是不可能的。
我编写了一个可以保持所需纵横比的工作脚本。
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);
}
}
如果您想使用不同的比例显示其他内容,可以再次使用function
keepAspectRatio(id, width, height);