Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to center an element

Short answer

Turn flexbox on at the parent and align along both axes:

<style>
  .stage { display: flex; justify-content: center; align-items: center; height: 120px; background: whitesmoke; }
</style>
 
<div class="stage">
  <div style="padding: 8px 16px; background: gold;">Centered</div>
</div>

justify-content moves the content along the main axis (horizontally), align-items along the cross axis (vertically).

The shortest variant with grid

In grid one property, place-items, aligns both axes:

<div style="display: grid; place-items: center; height: 120px; background: honeydew;">
  <button>Sign up</button>
</div>

A block horizontally

A block with a set width only needs automatic margins on the left and right:

<div style="width: 200px; margin: 0 auto; padding: 8px; background: lavender;">A centered block</div>

Text inside a block

text-align aligns text and inline elements:

<p style="text-align: center;">Centered text</p>

Common mistake

Vertical centering "does not work" when the parent has no height: a block exactly as tall as its content has nowhere to center things. Give the parent a height or min-height, as in the examples above. The second common mix-up is text-align: center on a block: it centers the text inside, not the block itself.

Functions used in this recipe

  • justify-content — Distributes items along the main axis of a flex or grid container.
  • align-items — Aligns items across the main axis — vertically in a row.
  • place-items — Sets `align-items` and `justify-items` at once.
  • margin — The outer spacing of an element — the distance to its neighbors.
  • text-align — Horizontal alignment of text and inline content inside a block.

Thanks for reading!

Donate to the site — we work hard for you.