Chapter 4: Modern Layouts (Flexbox and Grid)

Layout is the process of arranging elements on a page. Historically, this was a difficult task in CSS, often involving clever "hacks" with floats and positioning. Today, we have two powerful, native layout engines: Flexbox (for one-dimensional layouts) and CSS Grid (for two-dimensional layouts).

1. Flexbox: The One-Dimensional Powerhouse

Flexbox is designed to align items in either a row or a column. It is perfect for navigation bars, centering elements, and arranging items in a list. When you set display: flex; on a container, all its direct children become "flex items."

.container {
    display: flex;
    justify-content: center; /* Centers horizontally */
    align-items: center;    /* Centers vertically */
}

Key Properties: justify-content controls space along the main axis, while align-items controls space along the cross-axis. Mastering these two properties alone will solve 90% of your alignment headaches.

2. CSS Grid: The Two-Dimensional Powerhouse

While Flexbox is about rows OR columns, Grid is about rows AND columns simultaneously. It is the best choice for defining the overall structure of a page—like a dashboard, a photo gallery, or a magazine-style article layout.

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* Creates 3 equal columns */
    gap: 20px;
}

The fr (fractional) unit is a game-changer; it tells the browser to divide the available space into flexible parts, ensuring your layout remains responsive automatically.

3. When to Use Which?

A common question is: "Should I use Flexbox or Grid?"

4. Responsiveness with Media Queries

These layout tools work best with Media Queries. A media query allows you to change your layout based on the user's screen size. For example, you can switch from a 3-column Grid on a desktop to a single-column layout on a mobile phone.

Common Beginner Mistakes

Try It Yourself

  1. Create a navigation bar using a container with display: flex; and justify-content: space-between;.
  2. Build a 3-column photo gallery using display: grid; and the repeat(3, 1fr) syntax.
  3. Use a media query to change your grid from 3 columns to 1 column when the screen width is less than 600px.

Flexbox in Practice

Flexbox is designed for laying out items in a single direction — a row or a column — and makes centering content (once notoriously tricky in CSS) trivial.

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

When to Use Grid Instead

CSS Grid shines when you need two-dimensional layouts — rows and columns together — like a photo gallery or dashboard.

.gallery {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
}

A good rule of thumb: use Flexbox for components (like a navbar), and Grid for overall page layout.