How can an html element fill out 100% of the remaining screen height, using css only?
To use the entire screen height for an element, apply flex: 1
to the child element that needs to expand. The parent must have display: flex
and flex-direction: column
. No need to specify an additional height for the parent - flex: 1
will make sure the child takes up all remaining space once other siblings are accounted for.
The main content grows like a self-rising pizza to fill the space between header and footer.
Device compatibility
In the world of web design, there's no escaping the fact that you're dealing with a variety of devices. Using min-height: 100vh;
on your element will ensure it adjusts to various screen sizes, always taking up at least the height of the viewport. Alternatively, min-height: 100%;
on the body
tag offers a more consistent effect across old-timey browsers.
Got a fixed header? No problem - adjust the content height dynamically using the magic of calc
:
Defining a CSS variable --header-height
allows you to perform this useful calculation.
Tips for responsive design
Choosing flexibility
Flexibility is key in responsive design so opting for min-height
over height
lets content grow to fit without a JavaScript crutch. This approach aids the user by ensuring content does not overflow the viewport.
Managing overflow
When content is larger than the viewport, use overflow management with overflow: auto;
to ensure scrollbars only appear when needed:
Simplifying with containers
Putting the header and content inside a common ancestor can help tidy up your layout structure and make the document flow more palatable:
Overcoming CSS Limitations
Regarding compatibility
With great power comes great responsibility, and vh
units are no exception. If you're targeting grumpy old browsers (you know, the ones that got lost in 2011), you might want to have some fallbacks up your sleeve for legacy support.
Harnessing viewport units
Viewport units like vh
, vw
, and the rebellious vmax
offer dynamic scaling options perfect for modern responsive designs. However, vmax
is still grounded for bad behavior in certain browsers (ahem, IE).
Embraceing progressive content enhancement
Prioritising CSS over JavaScript not only enhances performance but also keeps code easy to maintain. JavaScript can come off the bench if CSS is falling short.
Was this article helpful?