Chapter 10

Positioning and CSS Grid

Move elements with the position property and build row and column layouts using CSS Grid.

Positioning and CSS Grid

Flexbox arranges items in one direction. This lesson covers two more layout tools: the position property, which moves individual elements, and CSS Grid, which lays out a page in rows and columns at the same time.

The position property

Every element has a position. The default is static. Other values change how the element is placed:

  • relative: keeps its normal spot but can be nudged with top, left, right or bottom.
  • absolute: removed from normal flow and placed relative to its nearest positioned ancestor.
  • fixed: stays in the same place on screen even when the page scrolls.
  • sticky: acts normal until you scroll past it, then sticks in place.
.banner {
  position: sticky;
  top: 0;
}
.badge {
  position: absolute;
  top: 8px;
  right: 8px;
}

An element with absolute looks upward for an ancestor whose position is not static. Giving a parent position: relative is the common way to create that reference box.

CSS Grid basics

Set display: grid on a container to turn its direct children into grid items. grid-template-columns defines the columns, and gap sets the space between cells.

.gallery {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

The fr unit means a fraction of the free space, so 1fr 1fr 1fr makes three equal columns. The repeat() function is a shortcut: repeat(3, 1fr) means the same thing.

Placing items and responsive columns

An item can span cells with grid-column, for example grid-column: 1 / 3 spans from line 1 to line 3 (two columns). To make a grid that fits as many columns as will comfortably fit, combine repeat with auto-fill and minmax().

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

Here each column is at least 200px wide but grows to share leftover space, and the browser decides how many columns fit.

Remember: Reach for Grid when you need rows and columns together, and Flexbox when items flow in one line. To position with absolute, give the parent position: relative first.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor