我看到了一个关于高度根据宽度而定的解决方案:css height same as width。或者在这里查看:https://dev59.com/t2035IYBdhLWcg3wZvFg#6615994。
但我的问题是相反的。
我的元素:
我的元素:
<body>
<div id="square"></div>
</body>
样式如下:
body, html {
margin: 0;
height: 100%;
min-height: 300px;
position: relative;
}
div#square { /* My square. */
height: 75%; /* It's height depends on ancestor's height. */
width: 75vh; /* If supported, preliminarily sets it's width. */
position: absolute; /* Centers it. */
left: 50%; top: 50%; transform: translate(-50%, -50%);
background-color: darkorange; /* Makes it visible. */
}
保持一致的脚本:
window.onload = window.onresize = function (event) {
var mySquare = document.getElementById("square");
mySquare.style.width = mySquare.offsetHeight + 'px';
};
完整的代码在这里:http://jsfiddle.net/je1h/hxkgfr9g/
问题是使用纯CSS实现相同的效果,不使用脚本。