CSS

Center Any Element Vertically and Horizontally

Master vertical and horizontal centering of any single element using CSS Flexbox or Grid. Provides robust techniques for aligning modals, loaders, and UI components perfectly.

.flex-container {
  display: flex;
  justify-content: center; /* Horizontally center */
  align-items: center; /* Vertically center */
  min-height: 100vh; /* Example: container takes full viewport height */
  border: 1px dashed #ccc;
}

.grid-container {
  display: grid;
  place-items: center; /* Centers both horizontally and vertically */
  min-height: 100vh; /* Example: container takes full viewport height */
  border: 1px dashed #ccc;
}

.centered-item {
  width: 150px;
  height: 100px;
  background-color: #007bff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2em;
}
How it works: This snippet demonstrates two common and effective ways to perfectly center a single element within its parent using CSS. The Flexbox method uses `display: flex` on the container combined with `justify-content: center` for horizontal alignment and `align-items: center` for vertical alignment. The Grid method uses `display: grid` and the more concise `place-items: center` property, which is a shorthand for both `justify-items` and `align-items`. Both approaches provide robust, cross-browser compatible centering solutions ideal for modals, loading spinners, or any UI component requiring precise alignment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs