簡體   English   中英

使可滾動的 div 占據剩余高度

[英]Make scrollable div take up remaining height

我正在嘗試使用非常簡單的布局制作一個頁面:一個位於一個位置的標題,以及在其下方滾動的內容。 標題 div 將是顯示其所有內容的未知高度。 我希望內容 div 占據頁眉底部和頁面底部之間的所有空間並且能夠滾動。

我對此有幾個限制:

  • 我不想使用固定或絕對定位來保持標題的位置,而是有一個完美高度的 div 顯示內容,並且只有那個 div 是可滾動的
  • 我不想設置max-height或任何其他需要了解標題 div 高度的屬性

我為實現這一目標而探索的兩種方法是使用表格布局和使用彈性框。 我還沒有設法使用這兩種方法中的任何一種進行滾動。 以下是兩次嘗試的代碼。 我正在使用反應。 任何指針將不勝感激。 謝謝!!

編輯:我確實使用內聯樣式成功地做到了這一點,並在生成標題后測量了它的高度。 這適用於桌面上的 chrome、android chrome 和 android 瀏覽器,但它在 ios safari 中失敗了。 我不知道它為什么壞了,我正在調試,但我更喜歡一個不需要內聯樣式的更干凈的解決方案。 謝謝!

反應元素:

var SimpleScrolly = React.createClass({
    render: function(){
        var lorem = "Lorem ipsum dolor sit amet... ";
        var sampleText = lorem + lorem + lorem + lorem;
        var sampleHeader = "this is a header!"

        return(
            <div className={"simple_scrolly"}>
                <div className={"header"}>
                    {sampleHeader}
                </div>
                <div className={"content"}>
                    {sampleText}
                </div>
            </div>
            );
    }
});

表格布局的樣式:

.simple_scrolly{

  display: table;
  height: 100%;

  .header{
    display: table-row;
  }

  .content{
    overflow: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    display: table-row;
  }
}

flex 布局的樣式:

.simple_scrolly{

  display:flex;
  flex-direction: column;
  align-items: flex-start;

  .header{
    flex-grow:0;
  }

  .content{
    overflow: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    flex-grow:1;
  }
}

沒有JS,它實際上是完全可行的。 您可以使用 flex-box 使用一點“hack”輕松地做到這一點。

我在你的彈性盒示例之上工作,你可以在我制作的這支小筆中看到它http://codepen.io/elleestcrimi/pen/LENQvr

整個想法是這樣的:

  1. header has flex-grow: 0 //This only fills up space as much as the content
  2. content has flex-grow: 1 //This way this fills up the space even if there is no content
  3. 將內容的所有子級放入一個名為#inner-content的新 div 中
  4. 您絕對放置#inner-content來填充#content ,並允許它滾動。
  5. 多田!

這是下面的代碼:

#header {
  flex-grow: 0;
}

#content {
  overflow: hidden;
  flex-grow: 1;
  position: relative;
}

#inner-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%; // this is needed if you are using any other element
}

暫無
暫無

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

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