How can I center a flex item both vertically and horizontally within its container?
Asked on Oct 07, 2025
Answer
To center a flex item both vertically and horizontally within its container, you can use the CSS Flexbox properties `justify-content` and `align-items` set to "center". This ensures that the item is perfectly centered in the flex container.
<!-- BEGIN COPY / PASTE -->
<div class="flex-container">
<div class="flex-item">Centered Item</div>
</div>
<style>
.flex-container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 200px; /* Example height for vertical centering */
border: 1px solid #ccc; /* Optional styling for visibility */
}
.flex-item {
padding: 10px;
background-color: #f0f0f0; /* Optional styling for visibility */
}
</style>
<!-- END COPY / PASTE -->Additional Comment:
- The `display: flex;` property on the container enables Flexbox layout.
- `justify-content: center;` aligns items horizontally in the center of the container.
- `align-items: center;` aligns items vertically in the center of the container.
- Ensure the container has a defined height to see vertical centering in action.
- This method is widely supported in modern browsers.
Recommended Links: