I have used a CSS Grid layout to display a Calendar, as described here. I was impressed by how easy it was to implement responsive behaviour with a grid, just by changing the ‘grid-template-columns’ value.
The other day, I decided to try CSS Grid as a way to lay out a WordPress page, and in this case one that uses a Genesis child theme. The layout of particular interest was in the body of the page, containing the content and sidebar.
The sidebar can be placed to the left or right of the content, according to theme customisation options in the admin UI. The stylesheets I’ve seen generally use “float: left” and/or “float: right” to achieve the layout.
Thing is, I’m not hugely fond of “float”, apart from quite limited contexts such as images in text blocks. I’ve often had problems with other page elements being affected by the float, which leads me to look for alternatives.
So the technique I’ve used is, first, to associate a grid-area with each of the two elements. Note that in Genesis at least, the elements are of the types <main> and <aside>.
main {
grid-area: main;
}
aside {
grid-area: aside;
}
Once these grid area names have been defined, they can be used to define the layout of the grid columns as follows:
.content-sidebar-wrap {
display: grid;
}
.content-sidebar .content-sidebar-wrap {
grid-template-columns: 66% 33%;
grid-template-areas: "main aside";
}
.sidebar-content .content-sidebar-wrap {
grid-template-columns: 33% 66%;
grid-template-areas: "aside main";
}
Note that Genesis handily assigns a class to the <body> element, to define the layout that the admin has selected. It’s either ‘content-sidebar’ or ‘sidebar-content’ in this case, but this approach would be easy enough to adapt for other scenarios.
This page itself uses the technique – take a look at the HTML/CSS sources for more detail.
For small / mobile devices, it’s straightforward enough – just apply “display: block” or something like that to the wrapping container.
Now, I must be honest and say that while this works really well, I have a niggling reservation. Many many years ago, we used HTML tables to apply structure and layout to web pages. It’s certainly not deemed best practice these days … use tables where you have tabular data, and nowhere else. Could the same be said of CSS Grids?