We'll use display: grid; to make our parent element into a grid container. Then, we'll use grid-gap to add a gutter between our elements. Finally, we'll use grid-template-columns, the repeat function and fr units to create equally sized columns for our layout.
Duration
2 min
Access
Free
Transcript
Available
We'll use display: grid; to make our parent element into a grid container. Then, we'll use grid-gap to add a gutter between our elements. Finally, we'll use grid-template-columns, the repeat function and fr units to create equally sized columns for our layout.
Video Transcript
Ali Spittel: I have some pre-written code in my HTML. I have six divs with a class card. Each one has Lorem ipsum text in it. They're all children of my main element which has the class card-container on it.
In my CSS, my card elements already have a width to them and a background-color for easy viewing. First, I'll take my main element with a class card-container and add display: grid to it so that it's a grid container. Then I'll add grid-template-columns: 1fr 2fr 1fr. You can see that now my cards each take up different width on my page.
Fr stands for fractional unit. Since I have four fractional units, 1 + 2 + 1, the first column takes up one fourth of the grid container. The second takes up two fourths or one half. The third takes up one quarter as well.
I can make this a little bit more clear by adding on a grid-gap. This will add a gutter in between each one of my cards. If I change my 2fr to 1fr, now each one of my cards takes up one third of the page.
I can also refactor this to use the repeat function. This is the same thing that I had before. If I changed the 3 to a 4, then I'd have four equally sized columns. If I change the 1fr to 200 pixels, then each one of my columns would be 200 pixels across. Change this back to what we want, which is three 1fr units.
To recap, I made my main card container into a grid container. I then added a grid-gap to make it so that there was a gutter between the elements. Finally, I added grid-template-columns: repeat(3, 1fr) to make it so that I have three columns in each row, each one taking up one third of the page.