12 Weeks

Day 9. Continuing CSS Grid Course

October 11, 2019

When we have elements that are more than our grid cells, we can configure if the new cells add up on the columns or rows by setting the grid-auto-flow. The default is row, but we can set it to column. We can use the grid-auto-flow-dense.

Fractional Units

The amount of space left after all the elements have been laid out. CSS will first lay out all explicit elements and calculate the amount of space left as 1fr.

Take for example

grid-template-columns: 200px 200px 1fr;

CSS will lay out the first 2 columns of width 200px each and the third will have a width of 1fr which is the space left after laying out the explicit elements.

If we specify more than 1fr, the remaining space will be shared between the remaining elements

grid-template-columns: 1fr 1fr

If we try to set values for grid-template-rows , nothing will happen.

grid-template-rows: 1fr 1fr 1fr

Nothing happens because there’s no explicit height set on the element. When we set a height, the grid-template-rows work.

.container {
    display: grid;
    height: 600px;
    grid-gap: 20px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
}

If we have auto, the width or height of the column will take the size of the content.

/* Auto keyword will make elements take up their original size*/ grid-template-columns: auto 1fr;

Using repeat() function

We can make use of the repeat function like so

/* Will result to 8 columns alternating between 1fr and auto width*/
grid-template-columns: repeat(4, 1fr auto);

/* Will result to 4 columns each having a width of 1fr*/
grid-template-columns: repeat(4, 1fr);

We can also mix the repeat() function with numbers

/* Will result in a 4 column grid with the first having 100px and others 1fr*/
grid-template-columns: 100px repeat(3, 1fr);

Sizing Grid Children

We can use the grid-column property of the grid child element to control the size of an element. If we use hard values, we could make all grid elements on the same row or column inherit the size of the element we set grid-column on.

/* A grid element that spans 2 columns */
grid-column: span 2;

/* A grid element that spans 2 rows */
grid-row: span 2;

The grid-column or grid-row is so powerful. It is a short hand for the values grid-column-start or grid-column-end.

/* This tells grid to start laying the element on the second track
and end at the 5th track*/
grid-column-start: 2;
grid-column-end: 5;

Here’s the same effect with short hand property

/* This will start the grid child at
track 2 and end it at track5 */

.grid-column: 2 / 5;

We can also do the same for grid-row too.

NB: This is only for grid children.


Quick and Scrappy notes from 12 weeks of learning UX Engineering for the web. More