Skip to content
Share
Explore
Posts

CSS Grid

What isn’t CSS Grid?

It’s not a table. They have some overlapping use-cases, but only in a strictly layout context, and no-one uses tables for layouts in 2022 - right.
It’s not a flexbox. Flexbox is great for laying things out in one direction, but you quickly find yourself nesting elements within elements and creating something that looks suspiciously like a table.

What is CSS Grid?

Full name is CSS Grid Layout. I didn’t know that at the time, but I struggled to try and make it do a few things that it isn't meant to to do, and that mane would have pointed me in the right direction.
From
:
CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.
Like tables, grid layout enables an author to align elements into columns and rows. However, many more layouts are either possible or easier with CSS grid than they were with tables. For example, a grid container's child elements could position themselves so they actually overlap and layer, similar to CSS positioned elements.
Grid allows you to define complex, two dimensional layouts in pure CSS that you can then slot your content into.

How do I use it?

We can create a super-simple grid and assign our grid numeric identifiers:
<html>

<head>
<style type="text/css">
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
grid-auto-rows: minmax(100px, auto);
}

.container>* {
background-color: aqua;
}

.title {
grid-column: 1 / 4;
grid-row: 1;
}

.left-nav {
grid-column: 1;
grid-row: 2 / 4;
}

.body {
grid-column: 2 / 4;
grid-row: 2
}

.footer {
grid-column: 2 / span 2;
grid-row: 3
}
</style>
</head>

<body>
<div class="container">
<div class="left-nav">
left-nav
</div>
<div class="title">
title
</div>
<div class="body">
body
<br />
<img src="https://c.tenor.com/_Vh1PQl3dvwAAAAC/squares-animation.gif" />
</div>
<div class="footer">
footer
</div>
</div>
</body>

</html>
Or, we can give our rows and columns named identifiers and refer to those instead:
<html>

<head>
<style type="text/css">
.container {
display: grid;
grid-template-columns: [nav] 1fr [body] 2fr;
gap: 10px;
grid-template-rows: [header] minmax(100px, auto) [body] minmax(100px, auto) [footer] minmax(100px, auto);
}

.container>* {
background-color: aqua;
}

.title {
grid-column: nav / -body;
grid-row: [header];
}

.left-nav {
grid-column: nav;
grid-row: body / span 2;
}

.body {
grid-column: body / -body;
grid-row: body
}

.footer {
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.