Relearning CSS layout

2 minute read

I read a lot of Jen Simmons’ stuff and I’m convinced by her words about flexbox and grid being a big deal. At the time of writing CSS grid has 87.29% browser adoption, and flexbox has 97.3% (caniuse.com). I don’t feel a need to support older browsers in the case of this website so I was open to all options when creating the layout. Learning both flexbox and grid I honestly preferred grid for the most part, especially debugging. Cheng Hui Jing wrote an article about the process in detail, but the useful thing for me was the simple addition of dashed lines which outline node borders.

Wrapping content

What really bummed me though, is that grid is fairly limited in how it handles wrapping containers. You can specify different column widths for example with grid but then it wont wrap. The wrapping magic comes from using repeat() notation. Let’s look at a simple example:

1
2
3
4
5
6
7
<!-- HTML -->
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
/* CSS */
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: rebeccapurple;
  height: 200px;
}

Example on codepen

The 4 containers here will wrap as expected but only because of the grid-template-columns: repeat(auto-fill, 186px) line. If we wish to create to make these containers different sizes then auto-fill is lost and wrapping fails. I know there are ways around this with selecting specific children and using grid-column: span [number] like this. But it just feels much less intuitive than just using flexbox.

I can see loads of uses for CSS grid, but it’s hard to imagine asymmetrical sections without relying on media queries to change the order of things. For this reason I decided to use flexbox, and the increased browser support was a bonus. This was of course just a personal choice, and I’ll likely write up more as I find cool use cases for grid or flexbox.

Resources for learning

I was surprised how many resources are online for learning this, and most of them are great. Here’s a few I found particularly useful:

Flexbox

Grid