How can I center a div both horizontally and vertically in HTML using flex utilities?
Asked on Sep 03, 2025
Answer
To center a div both horizontally and vertically using flex utilities, you can apply the CSS Flexbox layout model. This involves setting the parent container to display as flex and using alignment utilities to center the child element.
<!-- BEGIN COPY / PASTE -->
<div style="display: flex; justify-content: center; align-items: center; height: 100vh;">
<div style="width: 100px; height: 100px; background-color: lightblue;">
Centered Div
</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The parent div uses "display: flex" to enable flexbox layout.
- "justify-content: center" centers the child div horizontally.
- "align-items: center" centers the child div vertically.
- "height: 100vh" ensures the parent div takes the full viewport height, allowing vertical centering.
✅ Answered with HTML best practices.
Recommended Links: