Back to Tutorials

CSS Grid vs Flexbox Tutorial

Lesson 1 of 2: Flexbox Fundamentals

Progress50%

Flexbox Fundamentals

Flexbox is designed for one-dimensional layouts - either horizontal or vertical. It excels at distributing space and aligning items within a container.

Key concepts:
• Main axis and cross axis
• Flex container and flex items
• Direction, wrap, and justify properties
• Flexible sizing and alignment

Main properties:
• display: flex - Creates flex container
• flex-direction - Sets main axis direction
• justify-content - Aligns along main axis
• align-items - Aligns along cross axis
• flex-wrap - Controls item wrapping

When to use Flexbox:
• Navigation bars
• Centering content
• Equal height columns
• Space distribution
• Component layouts

Example

.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.flex-column {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.flex-item {
  flex: 1; /* Grow equally */
}

.flex-item-fixed {
  flex: 0 0 200px; /* Fixed width */
}

/* Responsive navigation */
.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
}

.nav-links {
  display: flex;
  gap: 2rem;
  list-style: none;
}

@media (max-width: 768px) {
  .nav-links {
    flex-direction: column;
  }
}

Exercise

Create CSS for a card layout with: 1. Flex container with 3 cards in a row 2. Cards should be equal width 3. Center the cards vertically and horizontally 4. Add gap between cards 5. Make it responsive (stack on mobile)

Lesson 1 of 2