🌱BeginnerCSS Flexbox

Flexbox Basics

Learn the core Flexbox model: flex container, flex items, main axis, cross axis, and the most-used flex properties.

Overview

Flexbox (Flexible Box Layout) is the go-to CSS layout system for arranging items in a row or column. It solves common layout challenges centering, equal spacing, vertical alignment that were difficult before it existed. Flexbox works on two roles: - **Flex container**: the parent element where you set `display: flex` - **Flex items**: the direct children of the container The container has two axes: - **Main axis**: the primary direction row (horizontal) by default - **Cross axis**: the perpendicular direction column (vertical) by default Core container properties: - `flex-direction` row, row-reverse, column, column-reverse - `justify-content` aligns items along the main axis - `align-items` aligns items along the cross axis - `gap` space between flex items - `flex-wrap` allows items to wrap to the next line

Key Points

  • •display: flex on the parent turns its direct children into flex items
  • •Default flex-direction is row (left to right)
  • •justify-content controls spacing along the main axis
  • •align-items controls alignment along the cross axis
  • •gap: 16px adds space between all flex items (no negative margins needed)
  • •flex-wrap: wrap allows items to flow to the next line

Examples

Horizontal navigation with justify-content

.navbar {
  display: flex;
  justify-content: space-between;  /* logo left, links right */
  align-items: center;             /* vertically centered */
  padding: 0 24px;
  height: 60px;
}

justify-content: space-between puts the first item at the left edge and the last at the right edge.

Centering with flexbox the most common use

.center-container {
  display: flex;
  justify-content: center;   /* horizontal center */
  align-items: center;       /* vertical center */
  height: 100vh;
}

This 5-line snippet centers any content perfectly something that was painful before Flexbox.

Card row with gap and wrap

.card-grid {
  display: flex;
  flex-wrap: wrap;    /* cards wrap to next line */
  gap: 24px;          /* space between cards */
}

.card {
  flex: 1 1 280px;    /* grow, shrink, min-width 280px */
}

"flex: 1 1 280px" means the card can grow and shrink but starts at 280px wide.

Common Mistakes

  • Setting display: flex on the child instead of the parent
  • Confusing justify-content (main axis) with align-items (cross axis)
  • Forgetting gap using margin hacks instead

Note

To vertically center any element inside a full-height container: display: flex; align-items: center; on the parent. This works even without setting height on the child.

Exercises

Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

Where do you set "display: flex" to create a flex layout?