We'll begin by adding a little CSS to automatically shade the grid items in alternating shades of gray. Use the CSS code to the left to take care of that.
Below is what you get in a browser.
So far, we haven't done anything with CSS Grid. We'll be using the grid container to define the number of columns and how rows will be built.
The container starts by declaring a display type of "grid" with display: grid. Next, we use grid-template-columns to indicate how many columns we want. In this case there are two values following the property meaning this will be a two column grid. The first column will use 70% of the space and the second column will use 30%.NOTE: Units could be percentages, pixels, rems or even a combination such as 120px 20% 2fr 1fr;. More on fr below.
grid-column-gap creates a gap between the columns and grid-row-gap creates a gap between the rows. You can control both with simply grid-gap: 1em.
Viewed in a browser, you'll see the 70%/30% split. Also notice that because there are four elements (divs) in the HTML, only the first two elements are on the first row.
The final two elements automatically placed themselves on the second row via CSS Grid's auto-placement algorithm. This is referred to as the implicit grid. We didn't have to explicitly say what rows the elements should go on. It was implied that the next elements would have to move down to the next row.
CSS Grid brought us a new unit called "fractional" or fr. An "fr" is a flexible sizing unit that can be used with other units, such as percentage, or alone. 1fr means the element should take up one fraction of the remaining or unassigned space.
In the example to the left, we've decided to use 3 columns, each using 1 fraction (1fr) of the available space. Notice too that instead of using both grid-column-gap and grid-row-gap, we have instead handled both with the shorthand property grid-gap.The result in a browser is shown below. Notice that with four elements, the fourth box is moved down to the second row.
The result in a browser is shown below.
The result in a browser is shown below.
The result in a browser is shown below.
As we learned earlier, we don't have to explicitly state the number of rows. Rows are "implicitly" created via CSS Grid's "auto placement algorithm."
There is also no need to specify a height for any of the grid elements or rows. That's because CSS Grid automatically expands the height of an element (box) to fit the content inside.Notice in the example below that grid item one has expanded its height to accommodate the increased content it holds. The other elements on that row also expand to the same height. This is something that was very difficult to do in the old days of "floated" layouts. (It was referred to as the Holy Grail Layout problem). With CSS Grid, it's a breeze.