Lesson · HTML & CSS Basics

Flexbox and grid layouts

Modern CSS layout tools arrange content without hard-coding every position.

What you will learn

  • Create a Flexbox row
  • Create a responsive Grid
  • Choose a layout model that matches the task

Arrange one dimension with Flexbox

Flexbox lays items out along a main axis and can align them across a cross axis. It works well for a row of navigation items or a group of buttons. Gap creates consistent space between items without adding special margins to the first or last child.

Arrange two dimensions with Grid

Grid defines rows and columns together, making it suitable for card collections and page regions. A flexible track such as minmax(0, 1fr) can share remaining space while allowing content to shrink. repeat and auto-fit can create a responsive set of columns with fewer viewport-specific rules.

Let content determine space

Fixed pixel positions are brittle when labels wrap or text is enlarged. Use flexible tracks, minmax, and gaps to describe relationships rather than coordinates. Test with a long title and a narrow viewport, not just the shortest content on a wide screen.

Choose the simpler model

Flexbox and Grid can overlap in what they can achieve. Choose based on the relationship you need to express: one axis or a row-and-column system. Avoid nesting several layout systems until the simpler structure is clear, and keep the source order logical for keyboard and reading order.

Check the smallest supported width

A flexible track can still overflow if an item has an unbreakable URL or a child with a large intrinsic minimum width. Use min-width: 0 on grid or flex children when content needs permission to shrink, and decide how long words or code should wrap. Test with realistic content, not only short labels.

Css example
.lesson-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
  gap: 1rem;
}
.navigation {
  display: flex;
  align-items: center;
  gap: 1rem;
}

Practice exercise

Lay out a set of lesson cards in columns that fit the available space, with consistent gaps.

Show a hint

Use Grid with auto-fit and minmax.

Show one possible solution

Set display: grid, use repeat(auto-fit, minmax(14rem, 1fr)) for columns, and add a gap.

Quick check

Which layout is a natural fit for aligning items along one axis?

Frequently asked questions

Can I use Grid for a single row?
<p>Yes. Both Grid and Flexbox can solve some of the same problems. Choose the tool whose mental model best expresses the layout and remains easiest to maintain.</p>