Container Units

Categories:
frontend
css

What can Container Units do?

  • Size any element based on the width of your grid’s columns and gutters.
  • Your element's nesting depth will never change it's size.
  • Build layouts by combining with grid, flex or… neither!
.panel {
    width: var(--column-unit); 
    /* or columns(1) */

    padding: var(--gutter-unit); 
    /* or gutters(1) */
}

.panel + .panel {
	margin-top: calc(3 * var(--gutter-unit));
	/* or gutters(3) */
}

Why are Container Units different?

CSS Frameworks like Bootstrap or Bulma share the same fundamental limitation – their grids rely on relative units.

Every time you want to set an element’s size to be 3 columns wide, that element must be the direct child of a container div.

<!-- Bulma -->
<div class="columns">
    <div class="column">…</div>
    <div class="column">…</div>
    
<!-- Bootstrap -->
<div class="container">
    <div class="col">…</div>
    <div class="col">…</div>
    
<!-- Foundation -->
<div class="row">
    <div class="columns">…</div>
    <div class="columns">…</div>

How do Container Units work?

Design Software holds a long established method for re-using specific measurements in a document – Rulers.

Those red lines across the canvas allow you to measure your elements – and quickly drag a shape between two or more points.

Layout Grids

More recent intepretations allow us configure a Layout Grid – a grid configuration of columns and gutters.

These are the foundations of Container Units — but when combined with CSS, offers much more flexibility than your design tool:

  • “Make this element's width span across 3 columns
  • “Set the header height to be 4 gutters

Configuration at the :root

By combining calc() and absolute units, we can define our grid at the very top of our document, and re-use and remix those measurements everywhere else.

Get started with Container Units

Define your grid proportions with 3 values

:root {
   --grid-width: 960;
   --grid-column-width: 60;
   --grid-columns: 12;
}

These values set how wide a Column is in proportion to your Grid. In the example above, the Column is 6.25%, or 1/16th.

Gutters are calculated automatically from the space left over - no worries!

Now we have our proportions, we can define a Container size.

Set your Container Width

Container Width must be set as an absolute unit – I would recommend viewport units or rems.

:root {
    --container-width: 80vw;
}

You can update your --container-width at any breakpoint – all of your Container Units will update accordingly.

@media (min-width: 1000px) {
  :root {
    --container-width: 90vw;
  }
}

/* need max-width? */
@media (min-width: 1400px) {
  :root {
    --container-width: 1300px;
  }
}

Container Units CSS — gist on GitHub

SCSS Functions — gist on GitHub