CSS Questions & Answers Logo
CSS Questions & Answers Part of the Q&A Network
Q&A Logo

How can I center a flex item both vertically and horizontally within its container?

Asked on Sep 25, 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`. These properties allow you to align items along the main axis and the cross axis, respectively.
<!-- BEGIN COPY / PASTE -->
    <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px; /* Example height */
        border: 1px solid #ccc; /* Optional: for visual reference */
      }
      .item {
        width: 50px;
        height: 50px;
        background-color: lightblue;
      }
    </style>

    <div class="container">
      <div class="item"></div>
    </div>
    <!-- END COPY / PASTE -->
Additional Comment:
  • The `display: flex;` property on the container enables Flexbox layout.
  • `justify-content: center;` centers the item horizontally.
  • `align-items: center;` centers the item vertically.
  • The container's height is set to ensure vertical centering is visible.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network