How can I center a child element both vertically and horizontally in a flex container?
Asked on Sep 27, 2025
Answer
To center a child element both vertically and horizontally within a flex container, you can use the CSS Flexbox properties. These properties make it straightforward to align items in the center.
<!-- BEGIN COPY / PASTE -->
<div class="flex-container">
<div class="child">Centered</div>
</div>
<style>
.flex-container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 200px; /* Example height */
border: 1px solid #ccc; /* Optional styling */
}
.child {
padding: 10px;
background-color: #f0f0f0; /* Optional styling */
}
</style>
<!-- END COPY / PASTE -->Additional Comment:
- Use "display: flex;" on the parent container to enable Flexbox.
- "justify-content: center;" aligns the child horizontally.
- "align-items: center;" aligns the child vertically.
- Ensure the container has a defined height for vertical centering to work.
- This method is widely supported across modern browsers.
Recommended Links: