How to Create Centered Content Vertically and Horizontally with Flexbox

Centering content both vertically and horizontally is a common challenge in web design. Flexbox, a CSS layout model, provides an easy and flexible way to achieve this. In this article, we’ll explore how to use Flexbox to create perfectly centered content.

Understanding Flexbox

Flexbox, short for Flexible Box Layout, is a CSS3 layout mode designed to distribute space along a single row or column. It makes aligning items straightforward and responsive, eliminating the need for complex CSS tricks.

Basic Flexbox Container

To start, you need a container element with display set to flex. This container will hold the content you want to center.

/* CSS for the container */
.centered-container {
  display: flex;
  justify-content: center; /* Horizontal centering */
  align-items: center;    /* Vertical centering */
  height: 100vh;          /* Full viewport height */
}

Implementing in HTML

Apply the CSS class to a container element, such as a <div>, and place your content inside.

<div class="centered-container">
  <div>Your centered content here</div>
</div>

Using Inline Styles in Gutenberg

If you’re working directly within Gutenberg, you can add inline styles to a Group block to achieve the same effect.

Set the Group block’s Layout to Flex, then configure the following options:

  • Horizontal Alignment: Center
  • Vertical Alignment: Center
  • Height: 100vh

This setup will center any content inside the Group both vertically and horizontally across the full viewport height.

Additional Tips

  • Use margin: auto; on child elements for additional centering control.
  • Combine Flexbox with media queries for responsive designs.
  • Experiment with flex-direction to change the layout from row to column.

Flexbox provides a simple yet powerful way to create centered layouts. With just a few lines of CSS or straightforward Gutenberg settings, you can ensure your content is perfectly aligned every time.