Connect with us

CSS

How to Center a Flex Container but Left-Align Flex Items in CSS

Spread the love

In modern layouts, using Flexbox is a go-to technique for aligning content. But what if you want to center a flex container inside its parent, yet left-align its items within it?

This is a common layout pattern—for example, centering a card row in the middle of the screen while keeping the text inside those cards aligned to the left.

In this article, we’ll break down how to center a flex container horizontally while keeping flex items aligned to the left.


🧩 The Layout Goal

Let’s say you want:

  • A flex container (like a row of cards) centered on the page
  • But inside that container, the cards should start from the left, not be spaced out or centered

Visual Example:

[               [Card 1][Card 2][Card 3]                ]
 ^ centered container       ^ left-aligned items

✅ Step-by-Step Solution

✅ 1. Use Flexbox on the Container’s Parent

To center the flex container itself:

.parent {
  display: flex;
  justify-content: center; /* center the flex container horizontally */
}

✅ 2. Create the Flex Container and Left-Align Its Items

.flex-container {
  display: flex;
  justify-content: flex-start; /* align items to the left */
  gap: 16px; /* optional: spacing between items */
}

🧪 Full Working Example

🖥️ HTML

<div class="parent">
  <div class="flex-container">
    <div class="card">Card 1</div>
    <div class="card">Card 2</div>
    <div class="card">Card 3</div>
  </div>
</div>

🎨 CSS

.parent {
  display: flex;
  justify-content: center; /* Center the container */
  padding: 40px;
  background-color: #f0f0f0;
}

.flex-container {
  display: flex;
  justify-content: flex-start; /* Align items to the left */
  gap: 20px;
  background-color: #fff;
  padding: 20px;
}

.card {
  width: 100px;
  height: 100px;
  background-color: #23ebff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

🧠 Why This Works

  • justify-content: center on the parent centers the entire .flex-container
  • justify-content: flex-start on .flex-container ensures items inside it start from the left
  • This gives you a clean, centered container with left-aligned child elements

📦 Bonus Tip: Use max-width for Better Control

Add a max-width to .flex-container for a responsive layout:

.flex-container {
  max-width: 800px;
  width: 100%;
}

This ensures the container doesn’t stretch too wide on large screens.


✅ Summary

TaskCSS Property
Center flex container in parentjustify-content: center on .parent
Left-align items in flex containerjustify-content: flex-start on .flex-container
Add spacing between itemsgap: 16px

Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *