CSS

Perfectly Center an Element with Flexbox

Learn to perfectly center any element both horizontally and vertically within its parent container using simple CSS Flexbox properties for clean and versatile layouts.

.container {
  display: flex;
  justify-content: center; /* Horizontally centers content */
  align-items: center;    /* Vertically centers content */
  min-height: 200px;      /* Example height for visibility */
  border: 1px solid #ccc;
}

.centered-item {
  width: 100px;
  height: 100px;
  background-color: #007bff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
}
/* HTML Structure */
/*
<div class="container">
  <div class="centered-item">Hello</div>
</div>
*/
How it works: This snippet demonstrates how to achieve perfect horizontal and vertical centering of an item inside its parent using Flexbox. By setting `display: flex` on the parent, its children become flex items. Then, `justify-content: center` aligns items along the main axis (horizontally by default), and `align-items: center` aligns them along the cross-axis (vertically by default), resulting in a perfectly centered item.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs