Introducing CSS Grid

I’m really excited about CSS Grid finally being available in most browsers and am looking forward to start using it. If you haven’t seen or worked with CSS Grid yet, here’s a quick introduction.

HTML code used for a quick common structure

<div class=”wrapper”>
 <header>header text</header>
 <nav>nav text</nav>
 <main>some main text</main>
 <div class=”first”>box 1</div>
 <div class=”second”>box 2</div>
 <div class=”third”>box 3</div>

Before setting up the grid, I like to use the full viewport and no margins for a quick reset:

.wrapper {
 min-height: 100vh;
 margin: 0;
 padding: 0;

Now you are ready to start the Grid…

display: grid;

Column and Row Tracks

To define your rows and columns, you need to add ‘grid-template-rows’ and ‘grid-template-columns’ which defines the tracks, as such:

grid-template-rows: 50px 100px;
grid-template-columns: 100px 300px 100px;

This gets you pixel-based sizes, however the real power of a flexible grid is using ‘fr’ for fractional units

grid-template-columns: 1fr 2fr 1fr

Fractional units get you flexible columns and rows

You can even mix-match your sizes:

grid-template-columns: 3rem 25% 2fr 1fr

MinMax Grid Tracks

If you want to define minimum or maximum sizes, you can do so using 2 arguments:

grid-template-rows: minmax(300px, auto);
grid-template-columns: minmax(auto, 500px) 1fr 1fr;

This is a powerful way add constraints in the flexibility of columns and rows.

Grid Gaps

you can add a gap

grid-gap: 20px 40px;

which is shorthand for a 20px gap in-between the column, and 40px gap in-between the row.

Naming Grid Areas

While you can position items by using Grid lines and numbering, like explained in this article, I find that the easiest solution for me is naming the Grid areas.

 “header header header”
 “nav main main”
 “first second third”
 “footer footer footer”

Using semantic markup to define the areas makes it super easy to manage and add items to those areas.
Here’s the flexible Grid in action with the final code:

See the Pen CSS Grid Named Template Areas by paul del signore (@pdelsignore) on CodePen.