Grid Your Lions for CSS Grid

I’m really excited about the CSS grid layout implementation that became widely available this month. I personally love the control of hand-coded layout. Imagine positioning elements using two dimensions instead of one and now you can throw out all your frameworks (but hang on to your Sass)!

Jen Simmons has been writing about and working with grid extensively and I’ve been learning from her demos and meetups. To dive into grid, I made a homepage using many of its new properties. Firefox Nightly has an inspector tool to help visualize grid layout. Herewith a few examples from my stylesheet.

Grid is not yet available in all browsers, so you ought to write a feature query to test whether the property is supported.

@supports (display: grid) {
  // code runs only if grid is supported //
}

I wrote CSS to use flex display if grid is not supported (not shown). I wanted a simple layout for my page: one column with multiple rows and plenty of whitespace to show off the beautiful background image. Here you can see I used grid-template-areas to name my row sections and grid-template-rows to define the height of each row using fractional units to calculate proportions. I added a gap of 6.66% between rows.

.container {
  display: grid;
  grid-template-columns: 1fr;  grid-template-rows: 2fr 1.5fr auto .75fr;
  grid-template-areas:
    "header"
    "content"
    "links"
    "footer";
    grid-gap: 6.66%;
}

Then, for the grid area “links”, I used a nested grid to generate boxes of a certain width to fill the width of a column. The browser computes how many full columns can fit within each row and automatically wraps overflow to the next line. Each list item will occupy one box in the grid. The columns are responsive to the viewport size and I do not have to write any media queries for this to be so.

.projects ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  grid-gap: 6.66%;
}

For the footer, I nested a grid for social media icons. Here I practiced using explicitly placed elements. First, I created a grid that has one row and five columns of equal width.

.social-icons {
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 5%;
}

Then I placed my email icon into the first row, first column, and GitHub link in the second column and so on.

.email {
  grid-row: 1 / 2;
  grid-column: 1 / 2;
}

.git {
  grid-row: 1 / 2;
  grid-column: 2 / 3;
}

The numbers above are not fractions, rather they delineate the starting and ending line numbers of the column in which the element ought to be placed. This is great for placing elements in exact locations on the grid. You can see the line numbers using Firefox inspector tool, but currently this feature is only available with the Nightly build.

Mar 23 2017