[英]Making div scrollable without setting height
如何使div可滾動,而無需對其高度進行硬編碼? 通常,當您要使div可滾動時,需要設置max-height,否則它將不斷擴大。
#element {
overflow:auto;
max-height: 100px;
}
就我而言,我希望高度不受父母高度限制(並且父母可以調整大小),而不是通過在CSS中進行設置。
這是JSFiddle: http : //jsfiddle.net/mbrnwsk/58qSc/1/
為了使#content
能夠延伸以填充父級中的剩余空間減去#title
元素的高度,可以使用CSS或JS來實現。 CSS解決方案很簡單,但是您必須調整top
的偏移量以確保其正確適合。 通過將其他三個偏移量(左,下和右)設置為零,我們由此強制#content
元素完全伸展。
#parent {
border: 3px solid;
height: 150px;
position: relative;
}
#content {
overflow-y: auto;
overflow-x: hidden;
background: cyan;
top: 16px; /* This is based on the assumption that #title has a height of 16px */
right: 0;
bottom: 0;
left: 0;
position: absolute;
}
http://jsfiddle.net/teddyrised/58qSc/3/
對於更敏感的解決方案,您將需要依靠JS來獲取#title
的高度,然后相應地設置#content
的top
屬性-這樣做的優點是,當視口大小改變時,以及#title
的高度#title
發生變化。
對於CSS,與上面的相同,但是我們刪除了top
聲明。 相反,我們將其委托給JS:
$(function() {
$("#parent").resizable();
// Function to set height
var setContentHeight = function() {
$('#content').css('top', $('#title').outerHeight());
}
// Recalculate when viewport changes
// You can also bind this function to events that manipulate the dimension of #title
$(window).resize(setContentHeight);
// Run once when DOM is ready
setContentHeight();
});
http://jsfiddle.net/teddyrised/58qSc/4/
基於JS的解決方案的優點是:
setContentHeight()
函數綁定到可以預見的任何事件來重新計算top
,這些事件將改變#title
的尺寸。 top
,當你改變的補白,邊距,高度(MIN-,MAX-或高度),行高值#title
,或任何其子女(如果存在的話)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.