Ask any question about CSS here... and get an instant response.
How can I center a flex item vertically and horizontally within its container using Flexbox?
Asked on Nov 10, 2025
Answer
To center a flex item both vertically and horizontally within its container using Flexbox, you need to apply specific CSS properties to the container. This involves setting the container as a flex container and using alignment properties.
<!-- BEGIN COPY / PASTE -->
<div class="container">
<div class="item">Centered Item</div>
</div>
<style>
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 200px; /* Example height */
border: 1px solid #ccc; /* Optional styling */
}
.item {
padding: 10px;
background-color: #f0f0f0;
}
</style>
<!-- END COPY / PASTE -->Additional Comment:
- Use "display: flex;" on the container to enable Flexbox.
- "justify-content: center;" aligns items horizontally in the center.
- "align-items: center;" aligns items vertically in the center.
- Ensure the container has a defined height for vertical centering to work.
- This method is simple and effective for centering a single item.
Recommended Links:
