CSS Grid Fundamentals
box-sizing: border-box;
That will just make sure that any time we add padding or a border to an element, it does not increase the size, so that when we are trying to divvy up the width of a container, then we have it there.
—
The whole idea behind CSS Grid is you take an element, dice it up into columns and rows (these things are collectively referred to as tracks). And then, once you have all of your tracks in your element, you can take your items and lay them out anywhere inside of this grid that we want, without any need for positioning (like position absolute/top/etc.)
As soon as you use display: grid;
on a container, all its direct children will be automatically considered as CSS Grid items.
Now simply displaying a grid on a container doesn’t do much. That’s because we yet have to slice and dice our container into something that has a bunch of columns or rows. The easiest way to achieve that is to explicitly say how big we would like each of those to be. For that use grid-template-columns:
and define all of the different columns that you’d want. So, let’s say you wanted 3 columns, each of them being 100px:
grid-template-column: 100px 100px 100px;
And what’s gonna happen is that browser is automatically going to take this container and say, well okay it needs to be 300px wide, because they only asked for 3 columns, each of them being 100px wide, and then it will take each of the grid items (each of the immediate children of the grid container) and its just gonna start to lay them out inside of the grid.
So the rows are automatically created as we go on.
Now, if they’re all squished together, we can add something called the grid-gap: 20px
and what’s that gonna do is it’s gonna give you some spacing in between each of your columns and rows.
<
You can specify different values for your columns, for example
grid-template-column: 200px 500px 50px;
And by default, the items that are inside of that cell are going to just be stretched across.
fr
unit will replace the need for percentages.
You can also use the auto
keyword and it will take the rest of the available space. (try out)
For example, maybe you wanted a thick sidebar of 300px, and then you just want the rest to be there.
Or you can use repeat()
. For ex, maybe you wanted 5 columns 100px each, so repeat(5, 100px)
. That’s going to just dice it up. It’s gonna repeat itself five time over for 100px.
Same thing goes for using rows. In the image above, we have defined 2 columns that go top to bottom, and then we’ve only defined 3 rows, and you see after that, they sort of just start to size themselves (and that’s the implicit grid).