Flexbox: center horizontally and vertically
Seeking to center content horizontally and vertically with Flexbox? The following CSS covers your needs:
Pair it with a simple HTML structure:
And voilà! Your element is centered on both axes with minimum fuss.
Dialing in the Details
The quick solution is perfect for a rapid result, but let's dive deeper for more robust centering across various scenarios.
Ensuring Full Height
For the flex container to cover the full height, set your html
and body
to have a height
of 100%
:
Adaptive Flex Container
What if the container's height is not fixed? Use min-height: 100vh;
:
Simplified Row Structure
Does .row
do anything except holding centered items? If not, drop it. Reducing wrappers simplifies markup.
Flexbox Toolset Mastery
Flexbox offers more than just centering. flex-flow
, flex-direction
, and flex-wrap
add superpowers to your layout abilities.
Alternatives to Center
Sometime different roads lead to Rome. Another effective way to center elements:
This is best for centering items in an already flexed parent.
In-depth Flexbox Guide
Flexbox isn't just about centering. It's instrumental for creating responsive designs. When coupled with media queries, flex properties maintain perfect centering across all devices.
Dealing with Multiline Flex Containers
When your flex items span across multiple lines, utilize align-content
to manage space distribution.
For Older Browsers
Did you know Flexbox is a youngster? Some older browsers are not friendly with it. Ensure graceful degradation by using display: table;
or positioning as alternatives.
Vendor Prefixes
During the Flexbox's adolescence, it was overweight with vendor prefixes. Now, utilities like Autoprefixer handle these for us.
Issues and Fixes
Every browser is a unique unicorn and Flexbox is not immune to their quirks. Here are a few things that might trip you up:
- IE10. This relic uses an older Flexbox syntax. Include
-ms-
prefixes to support it. - Safari 8. This browser occasionally disagrees with certain Flexbox properties. Frequent testing will save your sanity.
By catering for these, your centered content will shine in all browsers.
References
Was this article helpful?