DEV Community

Cover image for Back-to-Basics: CSS Grid Definitions: grid-template-areas
⚡️Ren⚡️
⚡️Ren⚡️

Posted on • Edited on

Back-to-Basics: CSS Grid Definitions: grid-template-areas

As we learned from the Rows & Columns only walk-through Grid is a layout model that allows for more control of sizing and positioning of boxes and their contents. Grid is also a 2d model allowing to define columns and rows in the initial grid definition. This is in contrast to the flexbox model that allows for building a grid by separating the definition of each row and column. However, I want to make sure you know that each model has its uses and is not necessarily better than the other. I digress, this is about CSS grid-template-areas, so let's get back on track...

Rory likes knowing things

Defining a grid and placing its items:

  • grid-template-areas

Grid Preview

A little note about grid-template-areas:

Typically you'll want to use grid-template-columns and grid-template-rows in conjunction with grid-template-areas to have a better definition of space otherwise the grid will fill in an automatic way unless you have heights and widths set on you grid items.

Now how do we get our Grid on with grid-template-areas??

First, let's set up our HTML and define our base Grid:

  • HTML:
    <div class="Grid">
    <div class="Item1"></div>
    <div class="Item2"></div>
    <div class="Item3"></div>
    </div>
Enter fullscreen mode Exit fullscreen mode
  • .Grid:
.Grid {
    display: grid;
    grid-gap: 0.5rem;
    grid-template-areas: "i1 i2  i2"  "i1 i3 i3"  "i1 i3 i3";
    grid-template-columns: 0.7fr 1fr 1fr;
    grid-template-rows: 0.5fr 1fr 1fr;
}
// I use grid-gap to give a defining space so that the content is easier to read.
// grid-template-columns and grid-template-rows are used also so I don't need to
// define heights and widths in my grid items
Enter fullscreen mode Exit fullscreen mode

Grid Areas Example

Placing our grid items in this configuration is a touch easier than defining their placement via the line reference, in this method we will use the attribute grid-area in each of our item's CSS definition referencing the area (i1, i2, or i3) that it will occupy.

.Item1 {
    grid-area: i1;
}
.Item2 {
    grid-area: i2;
}
.Item3 {
    grid-area: i3;
}

Enter fullscreen mode Exit fullscreen mode

After we place our items we wind up with:
Final Grid

Here's the pen:

Grid Definition using grid-template-area by Ren Estep (@ren_estep) on CodePen.

At this point, you're probably like how can CSS Grid get even more awesome but Can I use it ?
Can I use CSS Grid
Well, it's partially supported for IE11, but for safety sake, I highly suggest a polyfill.
(If you have a preferred polyfill post it in the comments)

Look for more on CSS Grid in the next week

Top comments (0)