The CSS Grid Format Module has revolutionized the best way web sites are constructed. It gives instruments that permit for superior layouts with out the difficult hacks and ingenious options of the previous.

On this introduction to Grid, we’ll stroll by way of the fundamentals of how Grid format works, and we’ll take a look at a lot of easy examples of the best way to use it in observe.

Desk of Contents
  1. Getting Started with Grid Layout
  2. Setting a Gap Between Grid Items
  3. Setting Up Grid Columns
  4. Organizing Grid Items into Rows and Columns
  5. Placing Grid Items on the Grid
  6. Placing Grid Items Using Named Grid Lines
  7. Placing Grid Items Using Named Grid Areas
  8. Using Media Queries with Grid Layout
  9. Changing the Display Order of Grid Items
  10. Responsive Grid Layout without Media Queries
  11. Overlapping Elements in a Grid
  12. Wrapping Up

Getting Began with Grid Format

A grid is a framework of columns and rows into which we are able to place content material. (It’s a bit like a desk format, however on steroids!)

Getting began with Grid is so simple as doing this:

.container {
  show: grid;
}

Now, the entire direct kids of the .container factor shall be “grid objects”. To start out with, they’ll simply seem as a bunch of rows in a single column, as proven within the demo under.

Within the instance above, we’ve a <div> factor that acts because the container. Inside it we’ve a number of parts, which at the moment are grid objects:

<div class="container">
  <header>header</header>
  <apart>apart</apart>
  <fundamental>fundamental</fundamental>
  <footer>footer</footer>
</div>

To this point, we haven’t achieved a lot, as we’d get the identical end result with out show: grid.

Additional studying:

Setting a Hole Between Grid Objects

Let’s first house our divs aside a bit with the hole property:

.container {
  show: grid;
  hole: 10px;
}

The hole property inserts house between the weather vertically and horizontally, as we’ll see shortly. (We will set totally different horizontal and vertical gaps if we have to.)

Additional studying:

Setting Up Grid Columns

Presently, we’ve an “implicit” grid — which means that the browser is simply determining a grid for itself, as we haven’t specified any rows or columns but. By default, we simply get one column and 4 rows — one for every grid merchandise. Let’s now specify some columns:

.container {
  show: grid;
  hole: 10px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

With grid-template-columns, we’re specifying that we would like 4 columns every with a width of 1fr, or one fraction of the obtainable house. (As an alternative of 1fr 1fr 1fr 1fr we might write repeat(4, 1fr) utilizing the very useful repeat() function.)

Now our grid objects are specified by one row, as proven under.

Additional studying:

Organizing Grid Objects into Rows and Columns

Now let’s manage our grid objects into rows and columns, as we’d see them on a normal net web page format.

Firstly, we’ll specify three rows with the grid-template-rows property:

.container {
  show: grid;
  hole: 10px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: auto auto auto;
}

If we add that line to the Pen above, not a lot will occur but, as we haven’t specified how we would like our grid objects to suit into these rows and columns. (Once more observe that auto auto auto could possibly be written as repeat(3, auto) utilizing the repeat() operate.)

Additional studying:

Putting Grid Objects on the Grid

Our browser’s developer instruments are available in very useful for understanding CSS Grid format. If we examine our code up to now, we are able to see the horizontal and vertical grid strains that outline our grid, as pictured under.

Horizontal and vertical grid lines, numbered from 1 to 4 in both directions

There are 5 vertical grid strains and 4 horizontal grid strains, all of them numbered. We will use these grid strains to specify how we would like our grid objects laid out.

Let’s first set the <header> factor to span the 4 columns and one row:

header {
  grid-column: 1 / 5;
  grid-row: 1;
}

This tells the <header> to start out on the grid column line numbered 1 and finish on the column line numbered 5.It additionally tells the <header> to start out on the first grid row line. As a result of an finish line isn’t specified, it simply spans to the subsequent row line, so grid-row: 1 is equal to grid-row: 1 / 2.

Let’s do one thing much like the <footer>:

footer {
  grid-column: 1 / 5;
  grid-row: 3 / 4;
}

The one distinction right here is that we’ve set the <footer> to take a seat between grid row strains 3 and 4.

Now let’s place the <apart> and <fundamental> parts:

apart {
  grid-column: 1 / 2;
  grid-row: 2 / 3;
}

fundamental {
  grid-column: 2 / 5;
  grid-row: 2 / 3;
}

The result’s proven within the Pen under.

We now have a versatile and responsive format with out hacky floats, overflows and different nightmares of the previous. If we add content material to our grid objects, they’ll increase to comprise that content material, and the side-by-side columns will all the time have equal top. (For these working with CSS within the noughties, attaining equal-height columns was a nightmare!)

Helpful issues to learn about numbered grid strains

For those who look once more on the picture above, you’ll see that, alongside the underside, the vertical strains are additionally named with unfavorable numbers. Every grid line has a constructive and a unfavorable quantity. This has a lot of makes use of, equivalent to when there are many grid strains and we don’t essentially know what number of there shall be. We might set our <header> factor to span all 5 columns with grid-column: 1 / -1, because the final vertical line is numbered each 5 and -1.

Grid additionally has a span key phrase, which we are able to use to inform a component to span a variety of rows or columns. An alternative choice for our <header> format could be to write down grid-column: 1 / span 4. This tells the factor to start out on the first grid line and span throughout all of our 4 columns.

Check out these variations within the Pen above.

Additional studying:

Putting Grid Objects Utilizing Named Grid Traces

We’ve seen the best way to manage parts on the grid utilizing numbered grid strains. However we are able to additionally give names to some or all of our grid strains and reference these as a substitute — which is usually a bit extra intuitive and save us from counting grid strains.

Let’s replace our format to incorporate some named strains:

.container {
  show: grid;
  hole: 10px;
  grid-template-columns: [aside-start] 1fr [main-start] 1fr 1fr 1fr [main-end];
  grid-template-rows: auto auto auto;
}

Within the code above, we’ve named simply three vertical grid strains. The names go in sq. brackets beside our column widths, representing our column strains.

We will now place a few of our parts on the grid like so:

header, footer {
  grid-column: aside-start / main-end;
}

apart {
  grid-column: aside-start; 
}

fundamental {
  grid-column: main-start / main-end;
}

We will see this code in observe within the demo under.

Additional studying:

Putting Grid Objects Utilizing Named Grid Areas

One of the vital attention-grabbing and “designer-friendly” options of Grid format is the flexibility to call grid areas — that’s, a number of cells within the grid — in a easy and intuitive approach, after which use these names to put out our grid objects. It really works like this:

.container {
  show: grid;
  hole: 10px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-template-rows: auto auto auto;
  grid-template-areas:
            "header header header header"
            "apart  fundamental   fundamental   fundamental"
            "footer footer footer footer";
}

Utilizing grid-template-areas, we’ve drawn up a easy textual content grid specifying how we would like parts laid out. Now we simply want to use these space names to our parts:

header {
  grid-area: header;
}

apart {
  grid-area: apart;
}

fundamental {
  grid-area: fundamental;
}

footer {
  grid-area: footer;
}

So, the <header> will span all 4 columns, the <apart> factor will simply sit within the first column of the second row, and so forth.

We will see this in motion within the Pen under.

This code is lots easier than what we had earlier — whether or not utilizing numbered or named strains. Utilizing named grid areas like that is nearly embarrassingly easy — like utilizing a WYSIWYG editor as a substitute of writing actual code. However be assured, it’s not dishonest! It’s simply tremendous cool.

Utilizing line numbers and named strains with grid areas

It’s value noting that we are able to additionally use line numbers and/or named strains to outline grid areas. For instance, as a substitute of utilizing the grid-template-areas property, we might simply do one thing like this:

header {
  grid-area: 1 / 1 / 2 / 5;
}

fundamental {
  grid-area: 2 / 2 / 3 / 5;
}

The sample is row-start / column-start / row-end / column-end. You’ll be able to try a demo of this on CodePen. Personally, I discover it actually arduous to recollect this sample of rows and columns, however the wonderful thing about Grid is that there are many methods to do the identical factor.

Altering the format of grid objects

In days of previous, if we determined sooner or later to vary the format of our web page parts, it will probably have led to lots of code refactoring. For instance, what if we wished to increase the <apart> factor right down to the tip of the format? With grid areas, it’s tremendous straightforward. We will simply do that:

.container {
  grid-template-areas:
            "header header header header"
            "apart  fundamental   fundamental   fundamental"
            "apart  footer footer footer";
}

We’ve simply eliminated a grid cell from footer and assigned it to apart, resulting in what we see within the Pen under.

We would even resolve that we would like an empty cell someplace. We do this by simply utilizing a number of intervals, like so:

.container {
  grid-template-areas:
            ".      header header header"
            "apart  fundamental   fundamental   fundamental"
            "apart  footer footer ......";
}

See for those who can predict the result of this, after which check out this CodePen demo.

Additional studying:

We frequently desire a totally different format on small screens — equivalent to stacking our grid parts in a single column. A straightforward approach to do that is to reorder our grid areas by way of a media question:

@media (max-width: 800px) {
  .container {
    grid-template-columns: 1fr;
    grid-template-areas:
              "header"
              "fundamental"
              "apart"
              "footer";
  }
}

We’ve now specified only a single column, and set the order of the weather in that column.

Press the 0.5x button on the backside the Pen above to see how the format responds (or view the Pen on CodePen and widen and slender the viewport).

Altering the show order of grid objects

We’re at a great level now to see how straightforward it’s to vary the show order of parts in Grid format. Within the instance above, our supply order is <header>, <apart>, <fundamental> and <footer>, however in our media question we’ve set the <fundamental> factor to look above the <apart> factor. It’s that straightforward to swap across the show order of parts with Grid! We might even utterly reverse the show order of all of them.

We will reorder grid parts even when not utilizing named parts. By default, grid objects are positioned in accordance with their HTML supply order. Additionally they have a default order of 0. We will use this order property to vary the visible association of parts. The decrease the order worth, the earlier a component seems. Even unfavorable integers can be utilized, so if our <fundamental> factor had an order of -1, it will seem first.

To order our parts as proven above, we might set the order worth of <fundamental>, <apart> and <footer> to 1, 2 and 3 respectively. (Take a look at this Pen for a reside demo.)

A phrase of warning, although: reordered parts is usually a nightmare for accessibility, with the main target leaping across the display unpredictably, so use it sparingly.

Additional studying:

  • The official specification for the order property.
  • The order property defined on MDN, together with a piece on accessibility issues.

We noticed above that we are able to make our format aware of totally different display sizes. Firstly, by setting column widths to versatile models like fr, the format can develop and shrink as wanted. Secondly, we are able to use media queries to reorganize the format at sure breakpoints.

Grid format has instruments that permit for format reflow with out the usage of media queries. Nonetheless, we are able to’t obtain this with the format we’ve been working with above. It solely works for less complicated layouts the place every column shares the identical width.

Take into account the next HTML:

<article>
  <div></div>
  <div></div>
</article>

Let’s sit these divs side-by-side on large screens, and stack on small screens:

article {
  show: grid;
  hole: 10px;
  grid-template-columns: repeat(auto-fit, minmax(min(250px, 100%), 1fr));
}

You’ll be able to see the end result within the Pen under.

(Once more, press the 0.5x button on the backside the Pen above to see how the format responds.)

That code is a little more superior, and we clarify it intimately in How to Use the CSS Grid repeat() Function. The principle objective of exhibiting it right here is to offer a way of what’s potential with Grid format.

Additional studying:

Overlapping Components in a Grid

As soon as we’ve created a grid format, we are able to do extra than simply allocate every grid merchandise to its personal separate grid space. We will simply set grid objects to share the identical grid areas, partially or in full. This permits us to create lovely, inventive layouts — with overlapping parts, and with none difficult code.

Let’s create a easy grid containing a picture and a few textual content that partly covers the picture. Right here’s the HTML:

<article>
  <img src="village.jpg">
  <div>The attractive village of Oia, on the island of Santorini, Greece</div>
</article>

Now we’ll assign some rows and columns which might be partly shared between the div and the picture:

article {
  show: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: 2fr auto 1fr;
}

img {
  grid-column: 1 / 3;
  grid-row: 1 / 4;
}

div {
  grid-column: 2 / 4;
  grid-row: 2;
}

The result’s proven within the following CodePen demo.

The div seems above the picture just because it comes after the picture within the supply order. We will change which factor seems over the opposite by making use of z-index. For instance, attempt setting a z-index of 2 to the picture within the Pen above; it’s going to now cowl a part of the div.

Additional studying:

Wrapping Up

This text is meant simply as a fundamental introduction to what CSS Grid format can do. The hope is that it’ll present a springboard for additional studying and discovery. And there’s a enormous quantity you possibly can study Grid.

Grid vs Flexbox

An everlasting query is whether or not we should always use Grid or Flexbox. It’s true that there’s some overlap between what these two format instruments can do. Usually, the place there’s overlap, it’s value doing a number of exams to see which has the higher toolkit in every explicit situation.

As a normal rule, although, bear in mind this:

  • Flexbox is especially designed for laying out parts in a single route (even when these parts wrap throughout strains).
  • Grid is designed for laying out parts in two instructions, in order that they’re aligned each horizontally and vertically.

Because of this, Grid is usually a greater possibility for whole-page layouts, whereas Flexbox is healthier for laying out issues like menus.

For a extra in-depth comparability of Grid and Flexbox, try Flexbox or CSS Grid? How to Make Layout Decisions that Make Sense.

Browser assist for Grid

Once we first printed this text — again in 2016 — Grid was pretty new to browsers, and assist wasn’t common. These days, all the foremost browsers assist Grid. There’ll nonetheless be a number of older browsers floating round that don’t assist it, however in lots of circumstances, these browsers will nonetheless show the content material effectively sufficient. One good catch-all strategy is to start out with a single-column format for cellular units that may function a fallback for browsers that don’t assist Grid format. The Grid types could be added in by way of media queries for browsers that do assist them — to be displayed on wider screens.

You’ll be able to try the newest browser assist for Grid on caniuse.

Studying assets for Grid

Lastly, let’s finish with some additional studying assets. Numerous superb individuals have supplied tutorials, movies, books and extra on Grid. Listed below are only a few:

  • CSS Master, 3rd Edition, by Tiffany Brown, is a good introduction to CSS, with in-depth steerage on the best way to use Grid and different format strategies.
  • The MDN Grid reference.
  • The Grid by Example website of Rachel Andrew. (Truly, Rachel Andrew has a lot of unimaginable articles, tutorials, movies and even a e-book on Grid format, and is a foremost professional on it. Googling “Rachel Andrew Grid” will deliver up tons of nice materials for studying Grid.)
  • The Layout Land YouTube collection by Jen Simmons. (Jen is one other title value googling.)
  • Kevin Powell presents a lot of unbelievable Grid tutorials on YouTube which might be value testing.
  • CSS-Methods offers A Complete Guide to CSS Grid, which is a extremely useful useful resource.