0
0
CssHow-ToBeginner · 3 min read

How to Center Horizontally Using Flexbox in CSS

To center content horizontally using flexbox, set the container's display to flex and use justify-content: center;. This aligns all child elements in the center along the horizontal axis.
📐

Syntax

Use the following CSS properties on the container element:

  • display: flex; activates flexbox layout.
  • justify-content: center; centers child items horizontally.
css
.container {
  display: flex;
  justify-content: center;
}
💻

Example

This example shows a box centered horizontally inside a container using flexbox.

css
html, body {
  height: 100%;
  margin: 0;
}
.container {
  display: flex;
  justify-content: center;
  height: 100vh;
  background-color: #f0f0f0;
  align-items: center; /* vertically center for better view */
}
.box {
  width: 150px;
  height: 150px;
  background-color: #4a90e2;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  font-size: 1.25rem;
  border-radius: 8px;
}
Output
<div class="container"><div class="box">Centered</div></div>
⚠️

Common Pitfalls

Common mistakes when centering horizontally with flexbox include:

  • Not setting display: flex; on the container, so flex properties don't work.
  • Using align-items instead of justify-content for horizontal centering (align-items centers vertically).
  • Forgetting that flexbox centers only the direct children of the container.
css
/* Wrong: align-items centers vertically, not horizontally */
.container {
  display: flex;
  align-items: center; /* This centers vertically, not horizontally */
}

/* Correct: justify-content centers horizontally */
.container {
  display: flex;
  justify-content: center;
}
📊

Quick Reference

Remember these key points for horizontal centering with flexbox:

  • display: flex; enables flexbox layout.
  • justify-content: center; centers children horizontally.
  • align-items controls vertical alignment, not horizontal.
  • Flexbox centers only direct child elements.

Key Takeaways

Set the container's display to flex to use flexbox layout.
Use justify-content: center to center child elements horizontally.
Do not confuse justify-content (horizontal) with align-items (vertical).
Flexbox centers only the container's direct children.
Always check that the container has display: flex for centering to work.