在不弄乱子元素布局的情况下降低 div 的高度

Decrease height like behavior of div without messing layout of child elements

我有一个父项 div,它有一个固定位置,还有一个子项 div,它有一个固定位置(可以更改)并且里面有文本。此子文本以父文本 div 为中心。

我想通过更改一些 CSS 来创建一个行为,当父 div "height" 减少时,带有文本的子 div 保持相同的位置如果父级 div 未覆盖它,则不会显示。

下面的代码片段显示了我当前的布局。

#parent {
  position:fixed;
  background:red;
  width:100vw;
  height:100vh;
}

#child { 
  color:black;
  font-family:Arial;
  position:fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
<div id="parent">
  <div id="child">
    <h1>
      TEST
    </h1>
  </div>
</div>

我希望通过改变一些 CSS 来实现的是这样的:

http://prntscr.com/bjin61

比如说当魔法值在 50% 左右时,它应该只显示黄色边框中突出显示的区域,文本被截掉(这很重要)。

您需要以绝对单位明确设置子位置,而不是父位置的百分比。如果将position设置为fixed,child将完全脱离parent,所以需要设置为absolute。最后,隐藏父级的溢出元素。

#parent {
  position:fixed;
  background:red;
  width:100vw;
  height:47vh;
  overflow: hidden;

}

#child { 
  background: yellow;
  color:black;
  font-family:Arial;
  position:absolute;
  top: 50vh;
  left: 50vw;
  transform: translate(-50%,-50%);
}
<div id="parent">
  <div id="child">
    <h1>
      TEST
    </h1>
  </div>
</div>