DEV Community

The daily developer
The daily developer

Posted on

CSS tutorial series: Grid Layout (Grid intro)

Instead of using positioning and floats, CSS provides a layout system that allows the use of rows and columns.

Like flexbox the grid layout consists of a container grid-container and children elements.

Similar to flexbox we use the display property in order to have a grid layout, along with other properties in order to effectively manipulate this layout.

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
</div>

Enter fullscreen mode Exit fullscreen mode
.grid-container {
  display: grid; 
}

Enter fullscreen mode Exit fullscreen mode

or

.grid-container {
  display: inline-grid;
}

Enter fullscreen mode Exit fullscreen mode

CSS grid columns and grid rows

Grid Column

Grid column

The grid Columns can be set using the property grid-template-columns which takes length units to specify the height of each column.

display: grid;
grid-template-columns: 200px 300px 800px;

Enter fullscreen mode Exit fullscreen mode

you want each of your column to be the same size instead of repeating the same value we can use a CSS function (We will discuss functions in another post) repeat(number of columns, height of your columns)

display: grid;
grid-template-columns: repeat(3, 200px)

Enter fullscreen mode Exit fullscreen mode

Grid row

Grid row

The grid rows can be set using the property grid-template-rows which takes length units to specify the height of each row.

Grid gap

This property specifies the space between each column and row in the grid.

Property Value
column-gap length unit
row-gap length unit
gap length unit
  • The row-gap property specifies the space or gap between rows.

  • The column-gap property specifies the space or gap between columns.

  • The gap property is a shorthand for both column-gap and row-gap properties.

Grid column/row start/end

grid-columns and grid-rows
The grid-column-start and grid-row-start properties specifies a grid item's starting position (where it starts).
The grid-column-end and grid-row-endproperties specifies a grid item's end position (until which line it should span)

  • grid-rows is a shorthand for the grid-row-start and grid-row-end properties.

  • grid-columns is a shorthand for the grid-column-start and grid-column-end properties.

grid-rows and grid-columns take two values each the first specifies the starting position and the second the end position like so:

grid-rows: 1/ span 3;
Enter fullscreen mode Exit fullscreen mode

The previous code will start on row one and span 3 rows. It works similarly with grid-columns but instead of spanning rows it spans the number of columns you specify.

Top comments (0)