如何让元素适配容器且不放大?CSS无JS实现方案求助
布局问题:实现类似
object-fit: scale-down的容器适配效果 现有一个包含header、content和footer的布局,content区域内有一排等宽的子项,每个子项包含一个子元素。要求子元素完美适配父容器,尽可能占满空间但绝不放大,效果类似图片使用object-fit: scale-down属性的表现。
需要适配的元素尺寸如下:
200 x 3001920 x 10801080 x 1920
期望实现的效果:子元素保持自身宽高比,在父容器内最大程度利用可用空间,但不会被放大超过自身原始尺寸,超出容器的部分不显示,整体居中于父容器。
目前尝试的代码无法正确实现,较大的元素要么溢出容器要么被裁剪,代码如下:
html, body { background-color: #000; height: 100%; margin: 0; padding: 0; } .layout { display: flex; flex-direction: column; height: 100%; } .top, .bottom { background-color: #444; flex-shrink: 0; height: 50px; } .middle { background-color: #222; flex-grow: 1; overflow: hidden; } .items { display: flex; gap: 20px; height: 100%; overflow: hidden; } .item { align-items: center; background-color: #666; display: flex; flex-grow: 1; justify-content: center; overflow: hidden; } .block { background-color: #f80; background-image: linear-gradient(45deg, orange, purple); height: 100%; width: 100%; } .block1 { max-height: 200px; max-width: 300px; } .block2 { max-height: 1080px; max-width: 1920px; } .block3 { max-height: 1920px; max-width: 1080px; }
<div class="layout"> <div class="top"></div> <div class="middle"> <div class="items"> <div class="item"> <div class="block block1"></div> </div> <div class="item"> <div class="block block2"></div> </div> <div class="item"> <div class="block block3"></div> </div> </div> </div> <div class="bottom"></div> </div>
综上,需要让固定尺寸的矩形仅能缩小、不能放大且保持宽高比,尝试过aspect-ratio属性也未成功,能否不通过JavaScript计算实现该需求?
内容的提问来源于stack exchange,提问作者Robo Robok
相关产品推荐
相关产品推荐

