Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

html - Prevent child div from expanding outside of parent?

Jsfiddle showing the issue: https://jsfiddle.net/ibrewster/g6v2x7ku/12/

Note how the pink div expands beyond the boarders of the blue div.

I'm trying to make a simple layout where I have two nested divs that expand up to a certain height (100% of the window height is desired in this case), with the inner div scrolling as needed to show additional content. So if the content is short, the divs all collapse down to the size of the content, but if it is long they only expand to a point, at which time the inner div should scroll.

The 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>

And the 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;
}

Note that the effect is the same if the max-height of topDiv is set to a percentage, under which scenario I can't simply set the max-height value of insideDiv to an appropriately smaller value. Also, setting the overflow property on topDiv to hidden doesn't work - the extra content in insideDiv is simply completely hidden then, not accessible by scrolling.

How can I limit the height of insideDiv to not exceed the height of topDiv, with insideDiv scrolling any extra content as needed?

question from:https://stackoverflow.com/questions/36609079/prevent-child-div-from-expanding-outside-of-parent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can change your #insideDiv's max-height CSS property from 100% to inherit. So this rule will be like this:

max-height: inherit;

You also might want to add box-sizing:border-box; if you go this route, as that will allow any borders or padding on #insideDiv to behave as (probably) desired.


The cause of this issue is that max-height:100%; looks for the parent's height, not its max-height for how tall it's allowed to be. Thus, you end up with the classic non-deterministic relative height problem. If you give the parent a deterministic height (rather than max-height), 100% can resolve deterministically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...