aspect-ratio-trick parent 的高度 100%

Height 100% of aspect-ratio-trick parent

我有一个 parent/wrapper 容器,其高度取决于宽度,因此它使用了常用于 iframe 和视频的有用 aspect-ratio trick;也就是说,设置 height: 0padding-top: 53.3% 为 16:9。

我现在的问题是我在需要 height: 100% 的包装内有一个 child。但它没有考虑填充,导致无高度 child 溢出。

此代码片段说明了我的问题:

let
 box = document.querySelector('.aspect-ratio')
;
document.querySelector('[name="toggle"]').onclick = function(){
 let
  padding_trick = 'height-0'
 ;
 if (box.classList.contains(padding_trick)) {
  box.classList.remove(padding_trick);
 } else {
  box.classList.add(padding_trick);
 }
};
* {
 box-sizing: border-box;
}

.controller {
 margin-bottom: 15px;
}

.wrapper {
 position: relative;
 width: 400px;
}

.aspect-ratio {
 background-color: beige;
}

.aspect-ratio.height-0 {
 height: 0;
 padding-top: 53.3%;
}

.inner {
 background-color: tomato;
 height: 100%;
 border: 1px solid #222;
}
<div class="root">
 <div class="controller">
  <button name="toggle">Toggle padding-trick</button>
 </div>
 <div class="wrapper">
  <div class="aspect-ratio height-0">
   <div class="inner">
    <p>Bordered content height is not 1oo%.</p>
   </div>
  </div>
 </div>
</div>

我想要的是文本出现在框内,红色 background-color 填满框的整个高度。

What I would want is that the text appears inside the box, and that the red background-color fills the entire height of the box.

这听起来像是您希望内框绝对定位在填充技巧框之上。如果是这种情况,只需添加 position 属性就可以做到这一点。

let
 box = document.querySelector('.aspect-ratio')
;
document.querySelector('[name="toggle"]').onclick = function(){
 let
  padding_trick = 'height-0'
 ;
 if (box.classList.contains(padding_trick)) {
  box.classList.remove(padding_trick);
 } else {
  box.classList.add(padding_trick);
 }
};
* {
 box-sizing: border-box;
}

.controller {
 margin-bottom: 15px;
}

.wrapper {
 position: relative;
 width: 400px;
}

.aspect-ratio {
 background-color: beige;
}

.aspect-ratio.height-0 {
 height: 0;
 padding-top: 53.3%;
  position: relative;
}

.inner {
 background-color: tomato;
 height: 100%;
 border: 1px solid #222;
}

.height-0 .inner {
  position: absolute;
  top: 0;
}
<div class="root">
 <div class="controller">
  <button name="toggle">Toggle padding-trick</button>
 </div>
 <div class="wrapper">
  <div class="aspect-ratio height-0">
   <div class="inner">
    <p>Bordered content height is not 1oo%.</p>
   </div>
  </div>
 </div>
</div>