Polytechnic

The personal brain-dump of Garrett Coakley

Oops!... I Grid It Again!

Today I replaced the Skeleton based layout on this site with a CSS Grid based layout. I’ve been wanting to make the move for a while and finally found the time after waking up at stupid o’clock this morning.

I wanted to do a like-for-like replacement and stick with the 12 column layout. I’m not quite ready for a complete redesign just yet.

Based on this clever repeating column trick from the Mozilla Developer Network this is how I went about it.

First up, create a 12 column grid I can add to any container I want:

.layout {
    display: grid;
    grid-template-columns: repeat(12, [col-start] 1fr);
    grid-column-gap: 2rem;
}

Taking a small-screen first approach, set the immediate children to span 10 of the columns, offset by one:

.layout > * {
    /* All grid elements to span 10 cols offset by 1 */
    grid-column: col-start 2 / span 10;
}

Adding my .layout class to the header and footer elements, and then wrapping main and aside in a div with that class gave me my basic layout. Then as the viewport gets wider, I can just do this on the required breakpoints:

@media screen and (min-width: 1000px) {
    .layout-main {
        grid-column: col-start 2 / span 5;
    }

    .layout-sidebar {
        grid-column: col-start 8 / span 4;
    }
}

I could have simplified the syntax and removed the line names by omitting col-start, but named lines are very powerful and I might want to play with them later.

The end result is my CSS payload has gone from around 20k to just under 6k, and my markup is a lot simpler.

It was ridiculously quick and painless. From branching my repository to deploying the final code took just over an hour, and I’m sure fifteen minutes of that was me double checking I hadn’t missed something. As Jeremy said :

I think I may need to recalibrate the estimation part of my brain to account for just how powerful CSS grid is.

(Thanks to Mat for pointing me towards to Pun Generator for the title)

Responses and comments

Likes

Comments

Marty McGuire on 23 Jul 2018