mentoor.io
CSS

CSS

How can you center an element horizontally and vertically in a container using Flexbox?

To center an element both horizontally and vertically using Flexbox, set the container as a flex container and use justify-content and align-items.

.container { display: flex; justify-content: center; /* Centers horizontally */ align-items: center; /* Centers vertically */ height: 100vh; /* Example height to demonstrate vertical centering */ } .item { background-color: lightblue; padding: 20px; }
  • justify-content: center; centers the items horizontally.
  • align-items: center; centers the items vertically.
  • This method works efficiently for centering content in both dimensions.
/ 29