I love the new layout modes in CSS. Grid and Flexbox are both amazing features. They each have their place. What if I told you that if you used the “wrong” one, you could double your CSS and HTML?
Let’s take a look at what appears to be a simple promo grid.
In this example, we have 4 promotional items. This stems from my time working in an agency setting. Every client wants a rotator at the top of their page. We would use asymmetric promotional spaces like this to work multiple calls to action into one area. This would allow us to avoid a carousel that we knew wouldn’t convert.
It’s important to give a user a sense of hierarchy with the design. To do that, we used different sizes to denote importance.
The design was done in Photoshop. This is really easy to accomplish in a design program.
At the time, we were still doing our primary layout in Flex. As it turns out, this is still quite complex in Flex.
Practical CSS Grid - Learn about this revolution in Web design!
Whether you're new to CSS Grid or have played with it, finding practical examples of this new layout mechanism is the best way to learn it's power. Sign up below for two hours of practical grid knowledge just for you!Start Learning Now!
The code required for Flexbox
It requires a lot of additional markup and quite a bit of extra CSS that is specific to the markup and display. In other words, the code was bloated and inflexible.
Our line count is at 12 lines of HTML and 40 lines of layout-based CSS.
The code required for Grid
Let’s take a peek at what we need to make this layout work with Grid.
No unnecessary nesting. Just four promo spaces inside of one container. This is the ideal amount of markup for this layout.
Because Grid allows us to specify our layout and flow our content into the layout, we’re saved many hacks that require additional markup.
The HTML line count is at six. Exactly half the line count of our flex example. Our CSS line count is at 20. Exactly half our CSS line count!
In this case, we use grid-gap to keep our margins clean, grid-template-columns to specify our column sizes and grid-template-areas to define areas we can place our content in.
Each promo gets its own named area with the grid-area property and that’s it. No more code necessary. This isn’t a hack. This isn’t the combination of layout tricks with additional markup. This is layout as a first-class citizen of the web.
Both these versions will work. Flexbox still has the edge in support. Think about this, though. If all things are equal, half the code with fewer hacks is much better to maintain long term. It’s all about picking the right tool for the job.
It’s an amazing time to be doing web design work. Things that weren’t possible before are. Things that were annoyingly difficult before are mind-bogglingly simple now.
What are some design patterns that were more annoying than they should have been that Grid makes super simple.