How to Center a Div

A comprehensive guide to all the ways you can center elements in CSS. Each method includes a live example and code you can copy.

Quick Summary

🎯 Best for most cases: Use Flexbox withdisplay: flex; justify-content: center; align-items: center;

📐 For grid layouts: Use CSS Grid withdisplay: grid; place-items: center;

📱 For horizontal only: Usemargin: 0 auto;on the child element

Flexbox (Recommended)

The modern and most flexible way to center elements. Works for both horizontal and vertical centering.

Centered Div
CSS:
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
Tailwind CSS:
<div class="flex justify-center items-center">
  <div>Centered Div</div>
</div>

CSS Grid

Another modern approach using CSS Grid. Great for more complex layouts.

Centered Div
CSS:
.container {
  display: grid;
  place-items: center;
}
Tailwind CSS:
<div class="grid place-items-center">
  <div>Centered Div</div>
</div>

Margin Auto (Horizontal Only)

Classic method for centering horizontally. The child element must have a defined width.

Centered Div
CSS:
.container {
  /* Parent doesn't need special styling */
}

.centered-element {
  margin: 0 auto;
  width: fit-content;
}
Tailwind CSS:
<div>
  <div class="mx-auto w-fit">Centered Div</div>
</div>

Absolute Position + Transform

Centers an element using absolute positioning. Works when you need to center over other content.

Centered Div
CSS:
.container {
  position: relative;
}

.centered-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Tailwind CSS:
<div class="relative">
  <div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
    Centered Div
  </div>
</div>

Text Align (Inline Elements)

For centering inline or inline-block elements horizontally within a parent.

Centered Div
CSS:
.container {
  text-align: center;
  line-height: 192px; /* Match container height */
}

.centered-element {
  display: inline-block;
  line-height: normal;
  vertical-align: middle;
}
Tailwind CSS:
<div class="text-center flex items-center justify-center">
  <div>Centered Div</div>
</div>

Flexbox with Direction

Using Flexbox with column direction and gap for multiple centered items.

Centered Div
CSS:
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 1rem;
}
Tailwind CSS:
<div class="flex flex-col justify-center items-center gap-4">
  <div>Centered Div</div>
</div>

Pro Tips

  • Always use Flexbox or Grid for modern projects - they're well-supported and flexible
  • Avoid using tables for layout centering - they're outdated and not semantic
  • Consider the context: horizontal-only vs. vertical-and-horizontal centering
  • Test your centering solution on different screen sizes for responsive design