CSS Grid Series: 2 - Fundamentals

Live dev notes taken throughout the CSS Grid course by Wesbos — cssgrid.io

CSS Grid effectively allows us to take any element on a page (such as <div>, <p>, etc) and display it as a grid.

The grid is made up of columns and rows (collectively known as 'tracks') which allows us to lay our items onto the grid without needing to define the positioning (i.e. top / left / bottom / absolute).

The size of the tracks can be defined by:

  • pixel (explicit)
  • percentage (implicit - but not ideal)
  • auto (implicit - calculates what's left over)
  • frames (implicit - best for responsiveness)

Create your containing element <div class="container">

Create a list of item elements inside the containing element with a class called 'item' <div class="item">. These are your grid items.

Slice and dice the container by applying display: grid. All elements secondary to the container are now defined as "grid items".

<head>
    .container {
        display: grid; 
    }
</head>

<body>
    <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
        <div class="item">6</div>
        <div class="item">7</div>
        <div class="item">8</div>
        <div class="item">9</div>
        <div class="item">10</div>
    </div>
</body>

To define 3 columns with a set width of 100px each:

<style>
    .container {
        display: grid;
        grid-template-columns: 100px 100px 100px;
    }
</style>

To define rows with set heights (will span across the page as 1 column):

<style>
    .container {
        display: grid;
        grid-template-rows: 400px 200px 100px;
    }
</style>

To define rows and columns:

<style>
    .container {
        display: grid;
        grid-template-columns: 100px 100px 100px;
        grid-template-rows: 400px 200px 100px;
    }
</style>

To space the grid items, add a gap spacing of 10px:

<style>
    .container {
        display: grid;
        grid-template-columns: 100px 100px 100px;
        grid-gap: 10px;
    }
</style>

To make one column responsive, use auto:

<style>
.container {
        display: grid;
        grid-template-columns: 100px auto 100px 100px;
        grid-gap: 10px;
    }
</style>

To repeat a single column, use the repeat() function:

<style>
    .container {
        display: grid;
        grid-template-columns: repeat(5, 100px);
        grid-gap: 10px;
    }
</style>

Any grid items that aren't counted in the rows or columns defined (i.e. a 3 by 3 grid has 20 items will lead to overflowing), will resize themselves based on the implicit tracks - more on that later on.