Container Units

Documentation for grid-based CSS layouts

Introduction

Container units are a specialized set of CSS variables that allow you to build grids, layouts, and components using columns and gutters.

They mirror the layout functionality found in UI design software where configuring just three values provides your document with a global set of columns and gutters to measure and calculate from.

Missed the intro? Start with the article on

Demo

See the Pen Container Units - Gist Demo by Russell Bishop (@russelllighthouse) on CodePen.

Download

Use with display: grid

First off, let’s start with the most 'normal' interpration. This is how most instances of a 'grid container' are used – a big div high up in the document.

Full Container

Some layouts may only ever use a grid container once – so here is everthing you'll need:

.o-grid {
width: var(--container-width);

display: grid;
grid-template-columns: repeat(var(--grid-columns), var(--column-unit)); 
grid-column-gap: var(--gutter-unit);
}

Partial grid container

When you want to use your grid measurements in a grid that isn't the full width of a container. This one's really easy, too.

.o-partial-grid {
width: columnspans(5); /* 5 columns + 4 gutters */

display: grid;
grid-template-columns: repeat(5, var(--column-unit)); 
grid-column-gap: var(--gutter-unit);
}

Use with display: flex

Flex Grids

This example is set up for instances where you can't know will be inside the grid – I've added some pseudo-random :nth() selectors to simulate this.

Note that flex-grow: 0; is set on the child elements. This is a stylistic choice – as I don't want each row to stretch and fill all available space in this example.

See the Pen Container Units - Flex Demo by Russell Bishop (@russelllighthouse) on CodePen.

Use with Gutters on the Outside

The default 'gutters inside' setup for Container Units may not suit the design that you're recreating. Here's how you can configure variations with different gutters:

Gutters outside (half width)

:root {
--grid-gutters: var(--grid-columns);
}

Gutters outside (normal width)

:root {
--grid-gutters: calc(var(--grid-columns) + 1);
}

Scrollbars and 100vw

Unfortunately for developers everywhere, there is a quirk to using viewport units that we have to work around. The scenario is:

  • The height of the document is greater than the device's viewport height, causing a vertical scrollbar
  • The operating system has a scrollbar that is not transparent
  • Your container width is above ~95vw at some breakpoints

Because browsers calculate 100vw as including the scrollbar, your 100vw-wide content will actually slide underneath your scrollbar and be invisible. This is not only unexpected behaviour (but apparently, correct?!), but tricky to overcome. But we can!

Javascript to the rescue

The talented John Evans (@burntcustard) has provided an excellent bit of javascript to measure var(--scrollbar-width).