CSS3 Grid Layout Tutorial

Datetime:2016-08-23 03:06:08          Topic: CSS3           Share

The CSS3 Grid Layout allows a more flexible positioning of DOM elements.

No more floats, yay!

Compatability

Actually, it’s an “experimental technology” currently and requires you to enable it in your browser first.

In other words you should NOT begin switching your float layouts to CSS grid layouts.

Here’s a browser compatability chart, but I’ll show how to enable it in Firefox and Chrome.

To enable grid layout in Firefox:

Type into the URL about:config

Click I’ll be careful, I promise!

Search for layout.css.grid.enabled

If the value is false switch it to true by double clicking it

To enable grid layout in Chrome:

Type into the URL chrome://flags

Search for Experimental Web Platform features and click Enable

Basics

I’ll be using the following

<div class="container">
  <div class="box one">one</div>
  <div class="box two">two</div>
</div>

Make the container display grid

.container {
  display: grid;    
}

By default display grid will place its child items into one single column

one
two

Using grid-template-columns inside the container you can specify the width of each column

.container {
  display: grid;    
  grid-template-columns: 100px 1fr;
}
one
two

Column one will have a fixed width of 100px and column two will take up the remaining space.

Let’s add more boxes to demonstrate rows

<div class="container">
  <div class="box one">one</div>
  <div class="box two">two</div>
  <div class="box three">three</div>
  <div class="box four">four</div>
</div>
one
two
three
four

We can also specify the height of each row using grid-template-rows

.container {
  display: grid;    
  grid-template-columns: 100px 1fr;
  grid-template-rows: 200px 1fr;
}
one
two
three
four

Lastly I’ll show how to switch the boxes around.

In this grid there are 3 column lines

one
two

And 2 row lines

one
two

Currently box one has a column start of 1 (the first blue line to the left of it) and column end of 2 (blue line on the right of it). Move it into box two’s position

.one {
  grid-column-start: 2;
  grid-column-end: 3;
}
one
two

This will take box two’s spot and thus gets pushed into the next row. Move it back up using grid-row-start / grid-row-end

.two {
  grid-row-start: 1;
  grid-row-end: 2;
}
one
two

And that’s the basics. For more info read Mozilla’s grid docs as well as Grid by Example

Thanks for reading!





About List