somascope
11/26/2018 - 8:39 PM

CSS grid examples

/* Set up grid and define the tracks */
.container {
  display: grid;
  grid-template-columns: ...
  grid-template-rows: ...
  
  /* Use repeat(qty, pattern) to declare multiple grid tracks*/
  grid-template-rows: repeat(4, auto); /* 4 horizontal tracks of height auto */
  grid-template-columns: repeat(3, 2fr 1fr); /* 3 tracks of pattern 2fr 1fr */
  grid-template-columns: 1fr repeat(3, 3fr) 1fr;
}


/* Create a 5x5 grid */
.container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 0.5em;
}

/* Simple example of responsive grid colums with mobile + 2 breakpoints */
.container {
  display: grid;
}
@media (min-width: 640px)
.container {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 768px)
.container {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

/* Placing content in the grid by using grid line numbers
Lines are numbered starting with 1 on the top left
Use negative numbers to start from the bototm right */
.item {
  /* grid-column: shorthand for grid-column-start & grid-column-end */
  grid-column: 1 / 3; /* span from grid line 1 to 3, or columns 1-2 */
  grid-row: 4 / 5;
}

/* Named grid lines */
/* two-column grid with three vertical grid lines named start, center, and end.
You can then reference these names instead of the numbers when placing grid items in your grid. */
grid-template-columns: [start] 2fr [center] 1fr [end];

To use: grid-column: start / center;

/* Using -start and -end suffixes */
grid-template-columns: [left-start] 2fr
                       [left-end right-start] 1fr
                       [right-end];
/* by naming grid lines left-start and left-end, you’ve defined an area called left 
  that spans between them. The -start and -end suffixes act as a sort of keyword 
  defining an area in between. If you apply grid-column: left to an element, 
  it’ll span from left-start to left-end. */
  
grid-template-columns: repeat(3, [col] 1fr 1fr) /* named as "col"
grid-column: col 2 / span 2 /* You can use "col" since you named it as such */

/* Named grid areas */
Setup:
grid-template-areas: "title title"
                     "nav nav"
                     "main aside1"
                     "main aside2";
                     
Use:
header {
  grid-area: title;
}
nav {
  grid-area: nav;
}
.main {
  grid-area: main;
}
.sidebar-top {
  grid-area: aside1;
}
.sidebar-bottom {
  grid-area: aside2;
}

/* Sizing in an implicit grid */
.portfolio .featured {
  grid-row: span 2;
  grid-column: span 2;
}