How can I center a div both vertically and horizontally using flexbox?
Asked on Oct 22, 2025
Answer
To center a div both vertically and horizontally using Flexbox, you can utilize the properties `justify-content` and `align-items`. These properties allow you to align items within a container efficiently.
<!-- BEGIN COPY / PASTE -->
<style>
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Full viewport height for vertical centering */
}
.centered-div {
width: 200px;
height: 100px;
background-color: lightblue;
}
</style>
<div class="container">
<div class="centered-div">
Centered Content
</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The `display: flex;` property on the container enables Flexbox layout.
- `justify-content: center;` aligns the child horizontally in the center.
- `align-items: center;` aligns the child vertically in the center.
- Setting `height: 100vh;` on the container ensures it takes the full viewport height, which is useful for vertical centering.
Recommended Links: