Explain Codes LogoExplain Codes Logo

Fill remaining vertical space - only CSS

html
responsive-design
css
flexbox
Alex KataevbyAlex Kataev·Oct 23, 2024
TLDR

To create a flexible layout and fill remaining vertical space, use CSS Flexbox. Assign the container with display: flex and flex-direction: column. For the child element that should expand, use flex-grow: 1:

.container { display: flex; // Setup the stage with Flexbox flex-direction: column; // Keep the actors in line height: 100vh; // Cover the whole stage } .main-content { flex-grow: 1; // The main actor takes up all available space! }

Don't forget to set height: 100%; and margin: 0 for the body to avoid default spacing issues and utilize full height coverage.

Foundation Setup

Ensure cover of the full viewport height:

html, body { height: 100%; margin: 0; }

This sets up a stable platform, preventing any unwelcome surprises from lurking default settings.

Alternatives & Fallbacks

Absolute Positioning

If Flexbox gives you a fright, (👻) you might find safe harbor with absolute positioning. It’s less flexible and responsive, but sometimes, simplicity is bliss!

#second { position: absolute; top: 200px; bottom: 0; left: 0; width: 300px; background-color: #9ACD32; }

CSS Disguised as a Table

Feeling nostalgic? Let's party like it’s 1999 with display: table properties:

.wrapper { display: table; width: 100%; } .row { display: table-row; } .cell { display: table-cell; }

Not quite as flexible as Flexbox, but it does the job!

Dealing with Fixed Items

Here’s our star actor .content between fixed-size .header and .footer, daring to push (or grow!) beyond its constricts.

.wrapper { display: flex; flex-direction: column; height: 100vh; } .header { height: 100px; // Fixed cap } .content { flex-grow: 1; // Anxious to expand overflow: auto; // For content that can’t help but spill out } .footer { height: 50px; // Fixed shoes }

Advanced Tactics

Responsive Audience Pleaser

Using percentage (%) or viewport height (vh) units for the container height can please varying audiences (screen sizes).

Nothing to Hide

Use background color to separate different sections and make sure each actor gets their own time in the spotlight!

<div id="first" style="background-color: #F5DEB3;">...</div>

Minimum Markup Maximum Impact

Simpler is often better, fewer divs mean fewer chances to trip up. It’s just like a Hollywood script...concise, powerful, and easy to work with.

Don't leave older browsers in the Stalls

Check if your Flexbox performance works well across all browsers, include prefixes or polyfills for better compatibility.

Practise your Performance

Wield tools like Jsfiddle to rehearse your layout and catch any blunders before you go live!