Experiments: CSS Grids

Four by four grid with three purple squares

Recently at work I had to adapt newer technology to older. One of the things that I had to do was to use the center hack with margin and width. I call it a hack because it is a hack, a lot of things that are standard now were once hacks because CSS was never perfect.

Also my experiments with CSS Grid were overdue, so why not try it since CSS Grids are almost production ready1. I have seen couple of interesting creations but nothing that I would routinely use at the moment (most of it is perfectly fine with flexbox because it is only in one dimension).

See the Pen A bit random CSS Grid by Sarah (@xgebi) on CodePen.dark

Let’s start with the centering the page. Normally you would do it with two lines of CSS code and one tag. With CSS Grids you need three lines but stating what you want is worth the extra line of code.

First we need to tell the browser to display CSS Grid. After that I chose to use 80% of the screen for the main content and two equal fr(actions) for the sides of the page. This does not mean that there have to be at least three elements on the page. One <div>  tag is more than enough, we just need to tell it to go straight to second column and stop before the third column. And the result with added color:

See the Pen CSS Grid Centering by Sarah (@xgebi) on CodePen.dark

Of course this isn’t everything that CSS Grids can do. One neat feature are areas. They are different from CSS Regions2. Grid areas allow you to make a more interesting template and assign specific areas specific elements.

See the Pen Third example of CSS Grid by Sarah (@xgebi) on CodePen.dark

If you go to the codepen and change your browser’s width you can see that there are two break points, one at 60em and the other at 30em. There is no special reason, it’s just for demonstration purposes. With every break point the structure is a little bit different. I made it to demonstrate that elements on the page get assigned areas but you can choose where those will be in grid template.

There are a lot of unexplored areas when it comes to CSS Grids including bugs, Rachel Andrew started a github for them.

For more information about CSS Grids MDN is the best resource I know about.

  1. Every current browser version except Edge supports it. Edge will support CSS Grids in the next release, hopefully this year.
  2. When I first met them I thought they were useless but after half an hour playing with CSS Grids more deeply than before I changed my mind.