[英]Scrollable child when max-height of parent is reached
My problem is quite similar to this one but the difference I can see is that my parent div ( #container
) have a min-height
and a max-height
(no height
as it should grow with its content), but the scrollable div ( #dynamic-part
) does not know its height
nor max-height
either.我的问题与这个问题非常相似,但我可以看到的不同之处在于我的父 div (
#container
) 有一个min-height
和一个max-height
(没有height
因为它应该随其内容增长),但是可滚动的 div ( #dynamic-part
) 也不知道它的height
也不知道max-height
。 It should be scrollable when its parent has reached its max-height
.当其父级达到其
max-height
时,它应该是可滚动的。
Is that something possible with pure CSS ?纯 CSS 可以实现吗?
HTML HTML
<div id="container">
<div id="fixed-part">
This will always be 60px big
</div>
<div id="dynamic-part">
This can grow and so should be scrollable<br><br>
<a href="#" onclick="addContent()">Add content</a><br><br>
<div id="insert">
</div>
</div>
</div>
CSS CSS
#container {
min-height: 100px;
max-height: 300px;
border: solid 1px black;
width: 200px;
padding: 0 5px;
}
#fixed-part {
width: 100%;
height: 60px;
border: solid 1px pink;
}
#dynamic-part {
width: 100%;
max-height: calc(100% - 60px);
border: solid 1px blue;
}
Here is a fiddle to help: https://jsfiddle.net/bz0b4ydz/这是一个帮助: https : //jsfiddle.net/bz0b4ydz/
If you use the flexbox model, then this is easy:如果您使用 flexbox 模型,那么这很容易:
var count = 1;//demo purpose function addContent() { let div = document.getElementById("insert"); divChild = document.createElement('div'); divChild.setAttribute('class', 'content'); divChild.innerHTML = 'New content ' + count; div.insertBefore(divChild, div.firstChild);// prepend new div count++ // demo update count }
#container { display: flex; flex-flow: column; min-height: 100px; max-height: 300px; border: solid 1px black; width: 200px; padding: 0 5px; } #fixed-part { flex-shrink: 0; /* or no height set but the full flex set : flex:1 0 60px;*/ height: 60px; /* can be avoid, see previous comment */ border: solid 1px pink; } #dynamic-part { flex: 1; border: solid 1px blue; overflow: auto; } .content { background-color: grey; width: 100%; height: 50px; margin: 5px auto; }
<div id="container"> <div id="fixed-part"> This will always be 60px big </div> <div id="dynamic-part"> This can grow and so should be scrollable<br><br> <a href="#" onclick="addContent()">Add content</a><br><br> <div id="insert"> </div> </div> </div>
You need a condition in your case :你的情况需要一个条件:
If( maxHeightReached ){ scrollable(); }
In that case, you could use javascript to keep track of an element's height.在这种情况下,您可以使用 javascript 来跟踪元素的高度。 But it's not easy to come up with a code here because it really depends on what you're trying to do.
但是在这里想出一个代码并不容易,因为它真的取决于你想要做什么。
Hope it helps.希望它有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.