Use CSS Flexbox to Center Anything Vertically & Horizontally 🎯 Like Images ️️🖼️, Text or DIVs Without Floats 🏊‍♂️ (Tutorial)

absolutely centering HTML DIVs and text using CSSFrustrated trying to use CSS to align center, like DIVs, images and text?

Like you aligning vertically and horizontally in HTML and CSS has been frustrating. I have used all sorts of unmanageable hacks over the years. But that has changed with the introduction of CSS Flexbox.

CSS Flexbox has made centering text, images and divs simple. That does not mean it is the only way to center content.

If you are like me you have scoured the web looking for the best solution to center horizontally and vertically in HTML.

I won't bother reviewing all the legacy hacks that involve margins, absolute or fixed positioning. They still work, but should be deprecated today.

Aligning Text

If you need to center text within an element like a div, header or paragraph you can use the CSS text-align property.

text-align has multiple valid properties:

  • center: text is centered
  • left: text is aligned to the container's left side
  • right: text is aligned to the container's right side
  • justify: text is forced to line up with the container's left and right edges, except for the last line
  • justify-all: forces the last line to justify it's text
  • start: same as left if language text direction is left to right. But right if the language text direction is right to left.
  • end: the opposite of start
  • match-parent: similar to inherit, except start and end are calculated with respect to the parent element

Use these properties to align text within the parent or wrapper div. This is nothing that exciting.

Horizontally Aligning Elements Using text-align

You can use the text-align property to align child elements.

A good example is to center a navigation bar or menu. This is can be frustrating because each menu item's width varies based on the text.

centered-navbar-html

Centering is easier when you know the exact widths of the parent and child elements.

center-aligned-text

You can apply the text-align: center rule to the navbar's wrapper element. The inner 'parent' element, a UL in this example, should be set to display:inline-block.

.navbar {
    text-align:center;
    width: 100%;
}
.navbar ul {
    display:inline-block;
}
.navbar li {
    float:left;
}
.navbar li + li {
    margin-left:20px;
}

To make the menu items look 'natural' float their position left.

Now you have a horizontally centered menu.

centered-navbar

This is a good way to center elements, but an old school hack.

Today we have a better way, CSS Flexbox.

CSS Flexbox

Flexbox was added to the CSS standards a few years ago to manage space distribution and element alignment. Basically it is a one-dimensional layout syntax.

When combined with the newer CSS Grid web developers have power syntaxes to make complex layouts simple to manage.

We say one dimensional layout control, but it really means both the x and y axis. As you will see alignment along each access is managed by different properties.

Flexbox is support by all modern browsers, including the soon to be eliminated Internet Explorer. So you can confidently use flexbox for CSS layout rules.

Center Text Horizontally and Vertically Using CSS to Center Align

Centering text in the absolute center has traditionaly been one of those common problems with clunky solutions Flexbox solves. In the past there were all sorts of hacks, like using display table, etc. Just like I mentioned earlier Flexbox has made this once complicated and unatural task simple.

First, lets look at some example markup to demonstrate how to center text horizontally and vertically.


    <div class="text-example">
        <h1>How to Center</h1>
        <h2>Anything with HTML & CSS</h2>
    </div>

This is a DIV with some header (H1 & H2) elements. The CSS we'll use not only centers horizontally, but vertically. You could enter any child elements, like a P or a SPAN here as well. The cool thing about the flexbox CSS properties used is they vertically and horizontally center anything!


    .text-example {
        <b>display: flex;</b>
        <b>align-items: center;</b>
        <b>justify-content: center;</b>
        <b>flex-direction: column;</b>
        width: 100%;
        text-align: center;
        margin: 10% 0;
        min-height: 200px;
        background-color: rgba(33, 33, 33, .3);
        align-items: center;
    }

This particular DIV is set to fill the width of the available space and be at least 200 pixels tall. That should give us some vertical margin to use in this demonstration.

The magic happens when you set the display property to flex. When the display is set to flex you can use more flexbox properties to direct the layout properties.

  • align-items
  • justify-content
  • flex-direction

align-items and justify-content are the imporant proeprties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items.

Not only can align-items be used to center text it vertically centers any child element.

There are other value align-items values:

  • stretch: Flex items are stretched such as the cross-size of the item's margin box is the same as the line while respecting width and height constraints.
  • start: The item is packed flush to each other toward the start edge of the alignment container in the appropriate axis.
  • end: The item is packed flush to each other toward the end edge of the alignment container in the appropriate axis.
  • flex-start: The cross-start margin edge of the flex item is flushed with the cross-start edge of the line.
  • flex-end: The cross-end margin edge of the flex item is flushed with the cross-end edge of the line.
  • self-start: The items is packed flush to the edge of the alignment container of the start side of the item, in the appropriate axis.
  • self-end: The item is packed flush to the edge of the alignment container of the end side of the item, in the appropriate axis.
  • first|last baseline: All flex items are aligned such that their flex container baselines align. The item with the largest distance between its cross-start margin edge and its baseline is flushed with the cross-start edge of the line.
  • safe center: If the size of the item overflows the alignment container, the item is instead aligned as if the alignment mode were start.
  • unsafe center: Regardless of the relative sizes of the item and alignment container, the given alignment value is honored.

The next few sections demonstrate how to use these properties in additional scenarios.

Horizontally Centering DIVs Using CSS Flexbox

Flexbox makes centering elements easy and natural.

Make the parent element's (.navbar) display flex. Set the width, in this example I want the navbar to stretch across the viewport, so 100%.

To center the child elements add the justify-content:center property to the parent element.

.navbar{
    display: flex;
    justify-content: center;
    width: 100%;
}

To make the CSS more reusable I broke the style rules into different selectors:

    .flex {
        display: flex;
    }

    .flex-horizontal-center {
        justify-content: center;
    }

This will come in handy as you build larger pages and need the same positining logic. I also like doing this because it makes reading the markup easy to correlate to how it should look.

vertically-centered-navbar

Vertically Centering DIVs Using CSS Flexbox

Horizontal centering has never been the hardest thing to accomplish.

But what about vertical centering?

For the most part this is where web developers and designers have lost their hair.

There are so many rules and hacks to memorize and even then something always seems to break the layout.

Flexbox has finally fixed vertical centering issues by making it an explicit rule.

Just like justify-content: center makes child elements center along the x-axis, the flexbox align-items:center rule centers the y-axis.

    .flex-vertical-center {
        align-items: center;
    }

In the header menu example the navbar wrapper element is centered vertically.

Here the header element wraps the navbar. Its width is set to 100% and the min-height to 80px;

{navbar with emphasized vertical center}

Since the navbar is shorter than 80px there is white space to work with. To make the navbar equally distant from the header's top and bottom make the header's display:flex and add the align-items:center rule.

Absolutely Centering DIVs Using CSS Flexbox

So far we have learned how to center elements either horizontally or vertically. Its time to combine both.

For this I will use the navbar. We want it to render in the absolute center of the Header element.

All you need to do is add both justify-content: center and align-items:center and flex-direction:column to the Header's CSS rules.

I added the flex-center CSS rule to help:

    .flex-center {
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }

You can use this combination of flexbox properties to center any element, not just navbars. Images, divs, etc can all be absolutely centered within a parent element.

{hero text overlay from other article}

You can see how I applied this principle to absolutely center text on a full screen background image.

How to Center an Image in CSS with text-align and Flexbox

Images can be aligned using both the text-align and flexbox properties.

Applying text-align to an image's parent element can be used to right, left or center align the image.

    .image-example {
        width: 60vw;
        min-width: 360px;
        text-align: center;
        margin: 5% auto;
        background-color: #ccc;
    }

You can also use right and left float to position an image along the desired container's edge. I tend to prefer using float because I align my images within my article text.

It is still harder to vertically align without flexbox. If you apply the absolute centering flexbox properties to the image's container you can center on both axis, or one if you choose.

Just for fun let's align an image using flexbox.

The same rules apply.

    Make the parent element's display flexThe parent element should have larger or equal dimensions than the imagealign-items and justify-content should be centerflex-direction set to column

centered-image-html

centered-image-example

Now the image is absolutely centered in the HTML element. You can adjust the CSS properties to make it either vertically or horizontally centered.

Wrapping it Up

Controlling element and text positioning is an important aspect of making a good layout.

In the past centering and aligning elements was frustrating and required a combination of hacks.

CSS Flexbox has changed the way we align elements. Now centering horizontally, vertically and both at the same time is simple.

Combining Flexbox positioning properties with text-align can make your layouts look great without cumbersome hacks.

The source code is available on GitHub!

Share This Article With Your Friends!