防止儿童div在父母之外扩张?

ibr*_*ter 20 html css

Jsfiddle显示问题:https://jsfiddle.net/ibrewster/g6v2x7ku/12/

注意粉红色div如何扩展到蓝色div的边界之外.

我正在尝试制作一个简单的布局,其中我有两个嵌套的div扩展到一定的高度(在这种情况下需要100%的窗口高度),内部div根据需要滚动以显示其他内容.因此,如果内容很短,则div全部折叠到内容的大小,但如果它很长,它们只会扩展到一个点,此时内部div应该滚动.

HTML:

<div id="topDiv">
  <div id="insideDiv">
    Some inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

而CSS:

html,
body {
  height: 100%;
}

#topDiv {
  background-color: lightblue;
  max-height: 50px;
  width: 100%;
  padding: 10px;
}

#insideDiv {
  background-color: pink;
  max-height: 100%;
  overflow-y:auto;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果将max-height topDiv设置为百分比,则效果相同,在这种情况下,我不能简单地将max-height值设置insideDiv为适当的较小值.此外,将overflow属性设置topDiv为隐藏不起作用 - 额外的内容insideDiv只是完全隐藏,然后滚动无法访问.

如何限制的高度insideDiv不超过高度topDiv,以insideDiv根据需要滚动任何额外的内容?

小智 30

您可以将自己#insideDivmax-heightCSS属性更改100%inherit.所以这个规则是这样的:

max-height: inherit;

box-sizing:border-box;如果你走这条路线,你也可能想要添加,因为这将允许任何边框或填充#insideDiv表现为(可能)所需.


这个问题的原因是max-height:100%;寻找父母的height,而不是它max-height的高度.因此,您最终得到了经典的非确定性相对高度问题.如果您给父母一个确定性height(而不是max-height),100%可以确定性地解决.

  • 可能还需要`box-sizing:border-box`,所以`#insideDiv`上的任何边框/填充更改仍然表现正常.至于为什么我发表评论而不是答案:我觉得在这里使用"继承"有点......哈哈?从技术上讲,你应该用这个设置把高度限制放在`#insideDiv`上,所以我不想说它"解决"了这个问题 - 更多只是解决了它.听到评论的赞誉,顺便说一下.没有足够的人这样做. (3认同)

Sti*_*ers 6

尝试这种flexbox布局,无论固定高度还是百分比高度/最大高度,它都能正常工作。

jsFiddle

html, body {
  height: 100%;
  margin: 0;
}
#topDiv {
  background-color: lightblue;
  max-height: 50%;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
#insideDiv {
  background-color: pink;
  overflow-y: auto;
}
Run Code Online (Sandbox Code Playgroud)
<div id="topDiv">
  <div>
    No scroll content
  </div>
  <div id="insideDiv">
    Some inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)