This is an attempt to demonstrate how CSS Grid Layout makes it possible to make a calendar with only three lines of CSS.

While many would argue that a calendar should be built semantically using a table, there are others who think a list would also be appropriate. And the <time> element could also be a potential solution for semantic calendars.

My choice for this CSS calendar tutorial is a list. Why? Because it’s the easiest way to show the amazing capabilities of CSS grid. Yes, making more complex calendars has been getting easier since flexbox, but CSS grid simplifies things even more.

Calendar with CSS Grid

Let’s start our demo with the HTML part:

<div class="calendar-wrapper">
  <ul class="calendar">
    <li class="weekday">Sun</li>
    <li class="weekday">Mon</li>
    <li class="weekday">Tue</li>
    <li class="weekday">Wed</li>
    <li class="weekday">Thu</li>
    <li class="weekday">Fri</li>
    <li class="weekday">Sat</li>

    <li class="first-day">1</li>

To emphasize the simplicity I kept the calendar in one list. But you use use two separate lists, an unordered one for the days of the week and an ordered one for the actual days.

The CSS part couldn’t be shorter:

.calendar {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
.first-day {
  grid-column-start: 3;

The first line is easy, it tells the browser to display the list as a grid. The second line, well, the second property, grid-template-columns, is used to define the size of each column. A week has seven days, we have seven columns. I could have easily written:

grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr;


grid-template-columns: 40px 40px 40px 40px 40px 40px 40px;

But that’s not only repetitive, it’s also prone to typos, so we can use repeat() because all our columns have the same width. The 1fr you see there is a new CSS unit of flexible length, you can read more about it here.

Finally, because most months don’t start on Sunday, we can use the grid-column-start property to specify which day is the first of the month.

There you have it: three lines of CSS to make a calendar. I encourage you to visit MDN and read more about CSS grid and all the things it can do.

See the Pen
Simple Calendar With CSS Grid
by Calendar Tricks (@calendartricks)
on CodePen.

Source link

Write A Comment