CSS grid is really interesting, and some interesting page layouts can be implemented with the CSS grid. This is very helpful for front-end development and to prevent unexpected misalignment. This time I’m going to share my tricks and tips in learning CSS Grid.
First let us look at the diagram shown below, and take a second to think what would you do to achieve the same layout.
You may want to set two different classes with height and width. You also need to do some math to ensure that all width and margin add up to 100%.
with CSS Grid You can avoid doing arithmetic problems and focus your attention on development.
grid-template-columns: 2fr 1fr;
In css grid, we will use the new property, grid-template-columns, grid-gap. And you may notice the value in grid-template-columns, 2fr 1fr. fr means fraction, same as 2/3, 1/3. Use css grid will calculate the percentage to determine the width! Let the computer do the work. Then, you can use grid-gap to add gap or whitespace between each box.
grid-template-columns: repeat(3, 1fr);
/* grid-template-columns: 1fr 1fr 1fr; */
grid-auto-rows: minmax(100px, auto);
/* grid-auto-rows: 100px; */
Here are something new. For example, repeat(3, 1fr). This is equivalent to writing 1fr 1fr 1fr, repeating 1fr 3 times. There is also grid-auto-rows: minmax(100px), set the minimum height to 100px, and the maximum height to automatic.
These are the basic tricks of the CSS Grid. I also added some interesting layouts by using CSS Grid in the code sandbox. If you are interested, feel free to open the following code sandbox link and add your custom code, or practice with CSS Grid. Good Luck! 🍀