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 Oct 04, 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 will align the item in the middle of the container.
<!-- BEGIN COPY / PASTE -->
    <div class="container">
      <div class="item">Centered Item</div>
    </div>

    <style>
      .container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px; /* Example height */
        border: 1px solid #ccc; /* Optional for visualization */
      }
      .item {
        padding: 10px;
        background-color: #f0f0f0; /* Optional for visualization */
      }
    </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.
  • `align-items: center;` aligns items vertically in the center.
  • Ensure the container has a defined height to see vertical centering.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network