Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

html - Set div to remaining height using CSS with unknown height divs above and below

Is it possible to make the wrapper fill the window height (no scrolling) and the center div scrollable without messing around with pixels and javascript?

<div id="wrapper">
  <h1>Header</h1>
  <div id="center">
    <div style="height:1000px">high content</div>
  </div>
  <div id="footer">Footer</div>
</div>

Basically I want the header to be visible at the top and the footer to be always visible at the bottom and have a scrollable content in the center which occupies the remaning height.
The header, footer and center divs' heights are all unknown (no set px or %, i.e. variable font-size or padding). Is it possible with pure CSS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

2014 UPDATE: The modern way to solve this layout problem is to use the flexbox CSS model. It's supported by all major browsers and IE11+.


2012: The correct way to do this with CSS alone is to use display: table and display: table-row. These are supported by all major browsers, starting with IE8. This is not using tables for display. You'll use divs:

html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: table;
    height: 100%;
    width: 100%;
    background: yellow;  /* just to make sure nothing bleeds */
}
.header {
    display: table-row;
    background: gray;
}
.content {
    display: table-row;  /* height is dynamic, and will expand... */
    height: 100%;        /* ...as content is added (won't scroll) */
    background: turquoise;
}
.footer {
    display: table-row;
    background: lightgray;
}
<div class="wrapper">
    <div class="header">
        <h1>Header</h1>
        <p>Header of variable height</p>
    </div>
    <div class="content">
        <h2>Content that expands in height dynamically to adjust for new content</h2>
        Content height will initially be the remaining
        height in its container (<code>.wrapper</code>).
        <!-- p style="font-size: 4000%">Tall content</p -->
    </div>
    <div class="footer">
        <h3>Sticky footer</h3>
        <p>Footer of variable height</p>
    </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...