簡體   English   中英

達到父級最大高度時的可滾​​動子級

[英]Scrollable child when max-height of parent is reached

我的問題與這個問題非常相似,但我可以看到的不同之處在於我的父 div ( #container ) 有一個min-height和一個max-height (沒有height因為它應該隨其內容增長),但是可滾動的 div ( #dynamic-part ) 也不知道它的height也不知道max-height 當其父級達到其max-height時,它應該是可滾動的。

純 CSS 可以實現嗎?

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

#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;
}

這是一個幫助: https : //jsfiddle.net/bz0b4ydz/

如果您使用 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>

你的情況需要一個條件:

 If( maxHeightReached ){ scrollable(); }

在這種情況下,您可以使用 javascript 來跟蹤元素的高度。 但是在這里想出一個代碼並不容易,因為它真的取決於你想要做什么。

希望它有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM