Explain Codes LogoExplain Codes Logo

Flexbox: center horizontally and vertically

html
responsive-design
css
centering
Nikita BarsukovbyNikita Barsukov·Sep 14, 2024
TLDR

Seeking to center content horizontally and vertically with Flexbox? The following CSS covers your needs:

.flex-container { display: flex; /* Let's get flexible 😉 */ justify-content: center; /* Horizontally center */ align-items: center; /* Vertically center */ height: 100vh; /* Stretch it to viewport height */ }

Pair it with a simple HTML structure:

<div class="flex-container"> <div>Center me!</div> </div>

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%:

html, body { height: 100%; margin: 0; /* Yep, body has some unwanted luggage, let's drop it */ }

Adaptive Flex Container

What if the container's height is not fixed? Use min-height: 100vh;:

.flex-container { min-height: 100vh; /* If overflows, no worries, we got the whole viewport anyway */ }

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:

.flex-item { margin: auto; /* Auto margins for the win! */ }

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