← Back to all snippets
CSS

Perfect Centering with Flexbox for Any Element

Learn to perfectly center any block or inline-block element horizontally and vertically within its parent using a simple CSS Flexbox pattern.

.container {
  display: flex;
  justify-content: center; /* Horizontally center */
  align-items: center;    /* Vertically center */
  min-height: 100vh;      /* Example for full viewport height */
}

.centered-item {
  /* Your item styles */
  width: 200px;
  height: 100px;
  background-color: dodgerblue;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.5em;
}
How it works: This technique utilizes `display: flex` on the parent container. `justify-content: center` centers items along the main axis (horizontal by default for `flex-direction: row`), and `align-items: center` centers them along the cross axis (vertical by default). This provides a robust and widely used solution for perfect centering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs