Unays Learn · CSS

Lay out a page with CSS Flexbox and Grid

CSS controls how HTML looks. Flexbox and Grid are the two modern tools for placing things on a page. This guide shows when to use each one, with examples you can copy.

Adding CSS to a page

Put your styles in a file such as style.css and link it inside the <head>:

<link rel="stylesheet" href="style.css">

A CSS rule has a selector (what to style) and declarations (how to style it):

h1 {
  color: #17594f;
  font-size: 2rem;
}

Flexbox: one direction

Flexbox arranges items in a single row or column. It is ideal for navigation bars, toolbars and rows of buttons. Turn it on by giving the parent display: flex:

<nav class="menu">
  <a href="/">Home</a>
  <a href="/about/">About</a>
  <a href="/contact/">Contact</a>
</nav>
.menu {
  display: flex;
  gap: 16px;               /* space between items */
  justify-content: center; /* along the row */
  align-items: center;     /* across the row */
}

Remember the two axes: justify-content works along the main direction (a row by default), and align-items works across it. Change the direction with flex-direction: column.

Cards that wrap

To show cards that move onto a new line when the screen is narrow, let flex items wrap and give each a flexible base width:

.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.card {
  flex: 1 1 220px; /* grow, shrink, start at 220px */
}

Each card starts at 220 pixels wide, grows to fill spare space and drops to the next line when there is no room.

Grid: rows and columns together

CSS Grid places items in two directions at once, so it suits whole-page layouts and galleries.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 12px;
}

This creates as many columns as fit, each at least 180 pixels wide, sharing leftover space equally (1fr means "one fraction of the free space").

For a page with a header, sidebar, content and footer, name the areas:

.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 16px;
}
header { grid-area: header; }
aside  { grid-area: sidebar; }
main   { grid-area: main; }
footer { grid-area: footer; }

Making it work on phones

Use a media query to switch to one column on small screens:

@media (max-width: 700px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas: "header" "main" "sidebar" "footer";
  }
}

A simple rule of thumb: use Flexbox when you are lining things up in one direction, and Grid when you care about rows and columns at the same time.

Try it yourself

In Unays Code, build a page with a flex navigation bar and a grid of six cards that becomes one column on a phone. Next, make the page interactive with JavaScript basics.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].