簡體   English   中英

使div可滾動而不設置高度

[英]Making div scrollable without setting height

如何使div可滾動,而無需對其高度進行硬編碼? 通常,當您要使div可滾動時,需要設置max-height,否則它將不斷擴大。

#element {
    overflow:auto;
    max-height: 100px;
}

就我而言,我希望高度不受父母高度限制(並且父母可以調整大小),而不是通過在CSS中進行設置。

這是JSFiddle: http : //jsfiddle.net/mbrnwsk/58qSc/1/

height:100%;

將其設置為等於父母的身高。

在這里看到

編輯:注釋是正確的:需要向父級添加填充

#parent {padding-bottom: 1em;}

為了使#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的高度,然后相應地設置#contenttop屬性-這樣做的優點是,當視口大小改變時,以及#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.

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