27

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

 4 years ago
source link: http://www.js-craft.io/blog/four-lines-of-css-to-make-a-calendar-layout-with-css-grid/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

The final example will look like this.

zQrEZjV.png!web

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
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
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.

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK