Explain Codes LogoExplain Codes Logo

How can I combine flexbox and vertical scroll in a full-height app?

html
responsive-design
flexbox
css
Anton ShumikhinbyAnton ShumikhinΒ·Oct 10, 2024
⚑TLDR

Get a full-height layout coupled with a vertical scroll in flexbox using:

body { margin: 0; /* Default margin, who? */ height: 100vh; /* Fill the viewport */ display: flex; /* Unleash the power of flexbox */ flex-direction: column; /* Stack 'em up */ } .container { flex: 1; /* Grab the available space */ overflow-y: auto; /* The secret sauce for scrolling */ }

Include this in your HTML:

<div class="container"> Scrollable utopia lives here </div>

This makes the .container expand to fill the screen, leaving aside any fixed headers or footers. It takes up the scrolling baton if the content exceeds the viewport height πŸ‘.

Flexbox: the star of structure and spacing

Flexbox masters in structuring layouts and managing the space between elements. When we say flex: 1;, we mean that an element should swallow up as much space as it can. Confused why flex: none;? That's for elements that need to sit still like a well-trained puppyβ€”headers or footers.

πŸš€ Pro tip: Short on content? No worries. min-height: 100% to the rescue, preserving full height. Got loads of content? Let height: 0 work out a flex gym for your overflowing content.

πŸ’‘ Activate a scrollbar with overflow-y: auto;, not sacrificing the dynamic flex-item size.

Addressing minimum dimensions

No one wants a squished content view. Try min-height: 100px; instead of a rigid height. This approach marries flexibility with scrolling, only triggered when the content behaves like a naughty child escaping its boundaries.

.container { flex: 1 1 auto; min-height: 100px; /* Under this, we scroll! */ overflow-y: auto; }

Leaving outdated practices

Beware of long-forgotten flexbox fossils like display: box;. Stick to the flexbox latest to maintain modern, standard properties. It's like wearing this season's trends to stay fab πŸ’….

For the love of interactive components

The flexbox love affair doesn't end at static layouts, it goes hand-in-hand with interactive components too. Picture a chat app where messages need to stack from the bottom. Flex-direction: column-reverse; to the talking bot πŸ€–.

Embracing responsiveness

Flexbox adapts like a chameleon when it comes to responsiveness. Use media queries to twirl the flex properties like a ballerina 🩰. Keep your design fluid and resilient.

Catering for irregular content

If your content refuses to stick to a uniform size, flexbox can still make sense of the chaos. Use flex-wrap: wrap; to keep order and space things out evenly.