简体   繁体   English

具有扩展高度的 CSS 长宽比,用于溢出内容

[英]CSS Aspect Ratio with Expanding Height for Overflowing Content

I have a CSS aspect ratio preserving box, however I am trying to make it so the height of the box will expand if the child's height is greater than the aspect ratio's height.我有一个 CSS 纵横比保留框,但是我正在尝试使框的高度在孩子的高度大于纵横比的高度时扩展。

Here's what I currently have:这是我目前拥有的:

 const box = document.querySelector(".box"); const inner = box.querySelector(".box-inner"); const content = box.querySelector(".box-content"); function updateBox() { const innerRect = inner.getBoundingClientRect(); const contentRect = content.getBoundingClientRect(); const expandHeight = contentRect.height > innerRect.height; inner.style.paddingBottom = expandHeight ? "0" : "100%"; inner.style.height = expandHeight ? "auto" : "0"; content.style.position = expandHeight ? "relative" : "absolute"; } updateBox(); window.addEventListener("resize", updateBox);
 .box { width: 100%; max-width: 100px; background-color: pink; position: relative; } .box-inner { height: 0; padding-bottom: 100%; } .box-content { position: absolute; top: 0; left: 0; width: 100%; }
 <div class="box"> <div class="box-inner"> <div class="box-content"> <div style="width: 50%; height: 125px; background-color: rgba(255, 0, 0, 0.5)"> content </div> </div> </div> </div>

This works, however when the window resizes the box flickers.这有效,但是当窗口调整大小时,框会闪烁。 Is there a way to solve this?有没有办法解决这个问题?

>= (greater than or equal to) solves the issue >= (大于或等于)解决问题

contentRect.height >= innerRect.height

 const box = document.querySelector(".box"); const inner = box.querySelector(".box-inner"); const content = box.querySelector(".box-content"); function updateBox() { const innerRect = inner.getBoundingClientRect(); const contentRect = content.getBoundingClientRect(); const expandHeight = contentRect.height >= innerRect.height; inner.style.paddingBottom = expandHeight ? "0" : "100%"; inner.style.height = expandHeight ? "auto" : "0"; content.style.position = expandHeight ? "relative" : "absolute"; } updateBox(); window.addEventListener("resize", updateBox);
 .box { width: 100%; max-width: 100px; background-color: pink; position: relative; } .box-inner { height: 0; padding-bottom: 100%; } .box-content { position: absolute; top: 0; left: 0; width: 100%; }
 <div class="box"> <div class="box-inner"> <div class="box-content"> <div style="width: 50%; height: 125px; background-color: rgba(255, 0, 0, 0.5)"> content </div> </div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM