Tips & Techniques from a CSS-Tricks Grid Layout Tutorial
I recently watched this tutorial video by Chris Coyier on CSS-Tricks hoping to pick up a few interesting tips on CSS Grid. Not only did I learn some useful tips related to Grid but I also picked up a couple handy workflow techniques while watching Chris at work. Here are my highlights:
- At 4:30 Chris mentions (and I believe he credits Adam Argyle) how you can "Use CSS Grid just for the gap.” The gap feature is one of my favorite aspects of Grid…as you can quickly insert space between all of the elements in your container…and it never occurred to me to use it solely as a means of specifying “margins” for my markup. Very neat.
- At 6:40 Chris shows off a tip for toggling a class on an element that I'm going to start using all the time now. Instead of writing a JS function or using something like jQuery, all you have to do is add a simple inline onclick event onto the HTML element on which you want to toggle a class on and off. This is the syntax:
this.classList.toggle('className')Chris' use of this method is for adjusting the max-width of the
<body>container simply by clicking on it and applying a separate class. He says he uses this approach sometimes when testing responsive layout changes because it eliminates the need of dragging the browser window in and out to see the changes take effect. Super helpful!
- At 15:02 Chris shows a solution for a broken layout which occurred after changing the markup of the images and text to use
<figure>tags instead. Wrapping the images and paragraph tags into
<figure>tags caused the Grid logic to change the layout away from the intended result. To solve this, while still using
<figure>tags, Chris adds a
display: contents;declaration which I wasn't familiar with. That declaration essentially tells the browser to ignore the container and make the children elements act as the children of the next element up in the DOM. Once he adds that one line the Grid logic works again. There are some accessibility issues with this approach so while it seemingly works, it's one to use with care.
The whole video is worth watching just to see Chris solve the layout in real-time. He ends the video with an alternate solution to the broken layout using CSS Subgrid support, which currently only works in Firefox. Even though subgrid has yet to be more widely adopted by other browsers you can see the potential it has, especially in solving layout issues like the one in this video.