Skip to main content

CSS Grid

how to use flexbox

https://flexboxfroggy.com/

how to use grid

https://cssgridgarden.com/

One of the things that sets CSS grids apart from flexbox is that you can easily position items in two dimensions: columns and rows.

Responsive Units

  • fr (fractional)
  • grid-template-columns doesn't just accept values in percentages, but also length units like pixels and ems. You can even mix different units together.
#garden {
display: grid;
grid-template-columns: 100px 3em 40%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

grid-area

shorthand both grid-column and grid-row. grid-area accepts four values separated by slashes: grid-row-start, grid-column-start, grid-row-end, grid-column-end.

#water {
grid-area: 1 / 2 / 4 / 6;
}

grid-row-start

grid-row-start works much like grid-column-start except along the vertical axis.

#water {
grid-row-start: 3;
}

grid-column

Typing both grid-column-start and grid-column-end every time can get tiring. Fortunately, grid-column is a shorthand property that can accept both values at once, separated by a slash.

For example, grid-column: 2 / 4; will set the grid item to start on the 2nd vertical grid line and end on the 4th grid line.

#water {
grid-column: 2 / span 3;
}

span

Instead of defining a grid item based on the start and end positions of the grid lines, you can define it based on your desired column width using the span keyword. Keep in mind that span only works with positive values.

#garden {
display: grid;
grid-template-columns: 20% 20% 20% 20% 20%;
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column-start: 2;
grid-column-end: span 2;
}

grid-template-

repeat

previously we defined five 20% columns with the rule grid-template-columns: 20% 20% 20% 20% 20%;. This can be simplified as grid-template-columns: repeat(5, 20%);

#garden {
display: grid;
grid-template-columns: repeat(8, 12.5%);
grid-template-rows: 20% 20% 20% 20% 20%;
}

#water {
grid-column: 1;
grid-row: 1;
}

grid-template-rows / grid-template-columns

  • known as the explicit grid
  • Implicit Grid with grid-auto-columns and grid-auto-rows

place-content

flex-direction: row; 
box-sizing: border-box;
display: flex;
place-content: center;
align-items: center;
flex: 1 1 0%;