【发布时间】:2015-04-17 20:19:19
【问题描述】:
我看到了高度取决于宽度的解决方案:css height same as width。或在这里:https://stackoverflow.com/a/6615994/2256981。 但我的问题恰恰相反。
我的元素:
<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 做同样的事情。没有脚本。
【问题讨论】:
-
我不知道你是否可以在css中做到这一点。你可以试试css-tricks.com/snippets/css/a-guide-to-flexbox,但我不知道这对你有没有帮助。
-
我也认为这在纯 CSS 中是不可能的,尝试了很多次......我们必须等待才能设计动态完美正方形!我看到的唯一选择是您实际编写的 Javascript。
标签: css aspect-ratio