如何在flex item中约束响应式正方形且不超出分配尺寸?
概述
如何创建一个内部正方形,使其尽可能填充flex容器项,同时保持1:1的宽高比,且不会导致flex容器项超出其分配的尺寸?
目标
我想要构建这样一个布局:flexbox的header和footer高度自动计算,content区域填充剩余空间,整个flexbox刚好填满body,不会产生滚动或溢出。在content区域内需要一个div正方形,取宽度100%或高度100%中的较小值。

问题
我遇到的问题是:如果基于宽度设置正方形尺寸,当视口宽度大于高度时,正方形会迫使所在的flex容器项被撑开,导致整个flexbox/body/html超出设置的100vh;如果基于高度设置尺寸,只有在视口宽大于高时有效,反之就失效。
核心问题
如何创建一个内部正方形,使其尽可能填充flex容器项,同时保持1:1的宽高比,且不会迫使flex容器项超出其分配的尺寸?
已尝试方案
以下是我使用的代码及几种尝试过的变体。
<html> <body> <div class="container"> <div class="header">Header</div> <div class="content"> <div class="should-be-constrained-square"></div> </div> <div class="footer">Footer</div> </div> <style> * { box-sizing: border-box; } html, body { height: 100vh; margin: 0; } .container { display: flex; flex-direction: column; height: 100vh; } .header { flex: 0 0 auto; } .content { flex: 1 0; border: 2px solid black; } .footer { flex: 0 0 auto; } .should-be-constrained-square { width: 100%; aspect-ratio: 1/1; background-color: red; /* Also tried: https://tylerduprey-52451.medium.com/a-perfect-square-with-css-964499440998 width: 100%; height: 0; padding-top: 100%; */ /* And tried: https://dev.to/tchaflich/a-width-responsive-perfect-square-in-pure-css-3dao width: 100%; padding-bottom: 100%; position: relative; */ /* And tried: https://www.sodawebmedia.com/insights/create-responsive-square-css/ width: 100%; .should-be-constrained-square:after { content: ""; display: block; padding-top: 100%; } */ } </style> </body> </html>
内容的提问来源于stack exchange,提问作者Samuel Neff
相关产品推荐
相关产品推荐

