This article references the new CSS Grid Layout Module. More specifically, it covers the grid-template-areas property. It is a powerfuly property that lets you visualize your grid in your CSS and explictly place grid items in a named area.
Defining a simple grid.
As simple grid layout could be a page with a sidebar and large content container surronded by a header and footer.The basic markup would consist of something like this:
footer will span the full width of the container while the sidebar will take up about a 25% of the container and the content will fill the rest. To express this with
grid-template-areas I’ll need to apply the following CSS the the
- Set the
- Use the
grid-template-columnsproperty to set the number of coumns and define their width (in this exampe I’m using the new fr unit to set the width of the first column to 1/4 of the available width and content section to 3/4 of the available width.
grid-template-rowsproperty can be used to define the height of the rows. In this example the
footerwill take 4rem and 3rem respectivly and the body content will take up the remaining available space.
grid-gapproperty defines the grid’s gutters and is shorthand for
- This is the fun part.
grid-template-areasdefines the areas available in the grid. The name given to grid areas are arbitrary but should be sensible. The
grid-template-areasalso provides a crude visual representation of the page layout.
Child elements of a grid are assigned to their location using the
grid-area property on the child elements. This is a very simple example but it already demonstrates the power the CSS Grid Layout. Simply changing the name a classes
grid-area can drastically change the layout.
grid-area in the CodePen below can really mess with the layout. In a good way.
Creating a nested grid.
CSS Grid Layout Level 1 was initially meant to include subgrid layout as well but as Rachel Andrew has pointed out, this have been moved to Level 2 of the CSS Grid specification. However, creating a nested grid is a simple as applying
display: grid; to an element whose parent is a grid container. In this example the simple layout above will have its
content grid-area contain its own two-column grid.
The nested grid will now contain a two-column grid of items, each column will take 50% of available space.
Learn more about CSS Grid Layout.
Corrections or comment can be directed to my twitter account @jshvgt.
Send a response
If you've written a response to this post enter the url of your post and send it over.