Use display:flex to fill the remaining vertical space using CSS
P粉794851975
2023-08-23 22:23:14
<p>In a 3-row layout: </p>
<ul>
<li>The top row should be sized according to its content</li>
<li>The bottom row should have a fixed height in pixels</li>
<li>The middle row should expand to fill the container</li>
</ul>
<p>The problem is that as the main content expands, it squeezes the header and footer lines: </p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">section {
display: flex;
flex-flow: column;
align-items: stretch;
height: 300px;
}
header {
flex: 0 1 auto;
background: tomato;
}
div {
flex: 1 1 auto;
background: gold;
overflow: auto;
}
footer {
flex: 0 1 60px;
background: lightgreen;
/* fixes the footer: min-height: 60px; */
}</pre>
<pre class="brush:html;toolbar:false;"><section>
<header>
header: sized to content
<br>(but is it really?)
</header>
<div>
main content: fills remaining space<br>
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
<!-- uncomment to see it break - ->
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>
<!-- -->
</div>
<footer>
footer: fixed height in px
</footer>
</section></pre>
<p><br /></p>
<p><strong>Violin:</strong></p>
<ul>
<li>http://jsfiddle.net/7yLFL/1/ (running, less content)</li>
<li>http://jsfiddle.net/7yLFL/ (damaged, large content)</li>
</ul>
<p>I'm lucky enough to be able to use the latest and greatest CSS, regardless of legacy browsers. I think I could use flex layout to finally get rid of the old table based layout. For some reason it doesn't do what I want...</p>
<p>For the record, there are a lot of related questions on SO about "filling the remaining height", but none of them solve the problem I'm having with flex. Reference: </p>
<ul>
<li>Let the height of the div fill the remaining screen space</li>
<li>Fill remaining vertical space - CSS only</li>
<li>Does a div fill the remaining height/width of the container when sharing the container with another div? </li>
<li>Makes the nested div stretch to 100% of the height of the remaining container div</li>
<li>How to make a Flexbox layout occupy 100% vertical space? </li>
<li>Wait</li>
</ul><p><br /></p>
The following example includes scrolling behavior when the content of an expanded center component exceeds its bounds. Additionally, the center component takes up 100% of the remaining space in the viewport.
jsfiddle here
HTML examples that can be used to demonstrate this behavior
Simple: DEMO