Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Four lines of CSS to make a calendar layout with CSS grid

A calendar layout seems a perfect candidate to be using the CSS grid. Let's see how we can accomplish this with the minimum amount of code.

The final example will look like this.

And our HTML structure will be the following:

<div class="days-of-week-container">
      <div>Mo</div>
      <!-- the list continues -->
      <div>Su</div>
</div>
<div class="calendar-container">
  <div>1</div>
  <!-- the list continues -->
  <div>31</div>
</div>

In normal circumstances, we will not have to write by hand all the <div>1 ... 31</div> stuff. It will be generated by Javascript, but for the sake of the example, we will just use basic HTML and CSS.

We have two main sections, the days-of-week-container and the calendar-container. Both of them will be grids, with the right text-align:

.days-of-week-container,
.calendar-container {
  display: grid;
  text-align: right;
}

Now, if we take a look at our grid it's pretty clear that we will have 7 columns. It's a bit, troublesome to write by hand something like:

grid-template-columns: 30px 30px 30px 30px 30px 30px 30px;

So we can use just a simple repeat to set up our columns:

grid-template-columns: repeat(7, 30px);

Now, given the auto-placement of the elements in the cells, the days of the week and the actual calendar will be placed first to last in the 7 column layout.

See the Pen
Calendar
by JS Craft (@js-craft)
on CodePen.

But, what if the month does not start on Monday? We can just use the grid-column to move the placement of the first day in the calendar, and the auto-placement will take care of the rest.

.calendar-container div:first-child {
  grid-column: 7;
}

See the Pen
Calendar with starting date
by JS Craft (@js-craft)
on CodePen.

So, voila, another example of how much we can get done with CSS grid and just a few lines of code.