CSS Grid Guides
A small library that reveals CSS grid guides to aid in dev
Introduction
I’ve created a small JavaScript module that you can import into your projects to visualize CSS grids while developing. This is similar to how Sketch and other design tools allow designers to view/hide layout grids. The hope is that this will make our jobs a little easier, encourage the use of CSS grids, and ultimately lead to more beautiful websites. In the following post, I will:
- Walk you through how to use the library
- Drill into the code a bit to explain how it works
Getting Started
First, a note regarding in which situations this module will prove handy:
At the moment, and for the foreseeable future, CSS Grid Guides are only meant to be used by sites that handle grids in the same way they are handled in applications like Sketch or Figma. That is to say, this library assumes you’re using a CSS grid property called grid-template-columns
and repeating X amount of columns with an equal gap between them. As an example, this is what a typical 12 column grid looks like that will play very nicely with this library:
.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 20px;
}
If your grids are not built this way, you may consider reading my other article — One Grid to Rule them All. In that post, I make the argument that you should have one grid style for your entire website, much in the same way a designer uses a single grid.
Installation
Install the tool using npm npm i css-grid-guides
Import
Import the tool into the relevant fileimport { gg } from 'css-grid-guides'
Usage
Make sure that you’re not calling gg
until after the relevant DOM has loaded. This is important because this tool will be cloning DOM so it definitely needs to be there before you run it. There are several ways to skin this cat and it will depend on the framework you’re using. In vanilla JS, you might do something like:
window.addEventListener('DOMContentLoaded', () => {
gg() // your code here
})
You’ll notice above that we’re simply calling gg()
. That’s all you need to do to enable CSS Grid Guides with its defaults. Speaking of which, here are the defaults:
selector = ".grid"
color = "rgb(240,128,128)" // reddish
opacity = 0.3
showNumbers = true
selector
: The CSS selector used to query all the grid elements (string)color
: The background color of the grid guides (string)opacity
: The transparency of the grid guides (number)showNumbers
: Show the column count at the top of each column (boolean)
Of course, you can manually override any of those defaults:
gg({
selector: '.show-grid-lines',
color: 'blue'
})
Here, we’re updating the selector to match to.show-grid-lines
and changing the color of the guides to blue
, while keeping the other default settings.
Of course, you could more or less get all of the above from the README. So if you’re interested in some behind the scenes action, please read on.
Under the Hood
This is a pretty simple library — only about 48 lines in version 3.0.0. gg
is simply a function that takes an optional settings object. Each object property is also given a default value so that manually override specific properties.
const gg = ({
selector = ".grid",
color = "rgb(240,128,128)",
opacity = 0.3,
showNumbers = true,
} = {}) => { ... }
The next step is to query all grids on the page and loop through them
const grids = document.querySelectorAll(selector);
grids.forEach((grid) => { ... })
Next, we actually need to clone each grid
element. The idea is that we’re going to inject an exact clone of the grid
into each grid
. This clone will be used to make guides that perfectly align with the target grid
.
grid.style.position = "relative";
const clone = grid.cloneNode();
clones.push(clone);
clone.style.cssText = `position: absolute; width: 100%; opacity: ${opacity}; height: 100%; min-height: 20px; pointer-events: none`;
grid.appendChild(clone);
In the above snippet, we’re:
- Making the original grid relatively positioned so that we can absolutely position the clone inside of it. By doing this, we’ll be able to lay the grid guides over the content currently in the target grid.
- Cloning the grid and updating some CSS properties so that it can be layered on top of the current grid.
- Saving the clone in an array of clones, for use for cleanup later
- Inserting the clone inside of the target grid
At this point, we have an exact grid clone sitting on top of each grid. The final step in the process is to add and style the columns in order to create the guides.
Here we have a function called addColumn
. This function simply injects as many columns as possible into the grid until one of the columns falls to the next row. This is determined by looking at the offsetTop
of each column. If that value is greater than 0, it can be assumed that the column is on the next row. As a result, the extraneous column is removed and the recursive loop is canceled.
Finally, we need to handle the possibility that grids will change responsively. For instance, it’s totally possible to go from a 12 column grid to a 4 column grid on mobile. To handle this situation, we simply add a resize event listener that removes the previous clones and re-runs everything.
It basically looks like this:
window.addEventListener("resize", () => {
clear();
init();
});
And that’s it! If you have any feedback or issues please feel free to leave a comment here, create an issue in the GitHub repo, or submit a pull request. Like I said in the beginning, I hope that this library will help some people and/or that the explanation of its functionality proves to be educational.