Center text or a block element with CSS

In this article you will see how to center text or a block element. text-align property sets text alignment horizontally and vertical-align sets text vertically. With flex-box layout, it can be easily to center one or more block elements both horizontally and vertically.

Center text contents

Center text contents horizontally — use text-align property

The text-align CSS property sets the horizontal alignment of inline contents inside a block element or table-cell box. Below is an example to center text horizontally.

The effect:

I am centered horizontally

The code:

<div style="width: 20rem; height: 6rem; border: 1px solid #eee; padding: 1rem; text-align: center;">I am centered horizontally</div>

Center text contents vertically — use vertical-align property

The vertical-align CSS property sets vertical alignment of an inline, inline-block or table-cell box.

Center text vertically inside a line

The effect:

Default alignement Middle alignement:🟩

The code:

<p style="text-decoration: underline overline;">Default alignement <span style="vertical-align: middle">Middle alignement:🟩</span></p>

Center a multiple lines of text vertically inside a box

The effect:

I am vertical middle in a table layout of div element.

The code:

<div style="display: table; width: 20rem; height: 10rem; margin: 1rem;border: 1px solid #eee; padding: 1rem;">
  <p style="display: table-cell; vertical-align: middle">I am vertical middle.</p>
</div>

Center a block element

Center a block element horizontally with margin: 0 auto

margin: 0 auto lets the browser to select a suitable margin horizontally, this can be used to center an element.

The effect:

I’m a block element centered horizontally.

The code:

<style>
  .center-x {
    width: 20rem; padding: 1rem;
    margin: 1rem;
    border: 1px solid #eee;
    margin: 0 auto;
  }
</style>
<div class="center-x">
  I'm a block element centered horizontally.
</div>

Center a block element with flex-box layout

flex-box is a flexible layout and provides powerful alignment capabilities.

Center a block element both horizontally and vertically

The effect:

I’m a block element centered both horizontally and vertically.

The code:

<style>
  .flex-center-x-y {
    width: 100%;
    height: 30rem;
    margin: 1rem;
    border: 1px solid #eee;
    display: flex; /* Center items horizontally by default */
    justify-content: center; /* Center items vertically by default */
    align-items: center;
  }
  .flex-center-x-y div {
    width: 10rem;
    padding: 1rem;
    border: 1px solid #eee;
  }
</style>
<div class="flex-center-x-y">
  <div>I'm a block element centered both horizontally and vertically.</div>
</div>

The effect to center multiple block elements both horizontally and vertially in a column:

I’m a block element centered both horizontally and vertically.
I’m a block element centered both horizontally and vertically.

Resource