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.
Let’s start our demo with the HTML part:
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:
grid-template-columns: repeat(7, 1fr);
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.