CSS Grid : Quick Guide

 

CSS grid is one of the most powerful tools in CSS for building advanced layouts easily without using any CSS frameworks like Bootstrap, Foundation… It’s supported by major browsers (Chrome, Firefox, Safari) and for sure it’s the future of layouts building.

In this article, I’m gonna cover only the basics that will help you to get started with CSS Grid. And stay tuned I’ll work on a complete guide soon, make sure to subscribe to get the full guide.

Now let’s start our first CSS Grid!

Html Layout

<div class="grid">
 <div class="item-1 red">1</div>
 <div class="item-2 green">2</div>
 <div class="item-3 purple">3</div>
 <div class="item-4 yellow">4</div>
 <div class="item-5 orange">5</div>
 <div class="item-6 blue">6</div>
 <div class="item-7 pink">7</div>
 <div class="item-8 grey">8</div>
</div>

This is how it should look at the beginning.

css grid

 

Now let’s add some CSS to order our grid items

Columns and Rows

In this first example, I’m gonna add four columns and two rows using the CSS grid-template-column and grid-template-row properties each column will have a width of 25%, and each row will have a height of 10ems.

CSS Code

/* GRID */
.grid {
 display: grid;
 grid-template-columns: 25% 25% 25% 25% /* Four columns */;
 grid-template-rows: 10em 10em /* Two rows */;
}
.grid div{
 font-family: arial;
 font-size: 2em;
 color: rgba(0,0,0,.5);
}

So this is how it should be after Adding CSS :

See the Pen qVJGPK by MusamaM (@MusamaM) on CodePen.

You can add any value you want for example if you want the second row to have less height you can change the grid-template-rows property value to 10em 5em.

Let’s dive a bit!

Now let’s use two new properties grid-column-start and grid-column-end to order and resize the grid items.

Before starting our second example I’m gonna explain what these properties mean.

The first one is grid-column-start it’s the first line from the grid as you can see in the image below I represented it with a green line.

The second one grid-column-end it’s the last line from the grid I represented it with the purple line.

grid colum start

Example two

Now let’s start our example by doing some little changes based on the first example, this time we will change the number of columns from four to three columns and we will make the first and the last items ( .item-1 and .item-8 ) having a full width by using the properties grid-column-start and grid-column-end, and for the row, I’m going to reduce the size just to fit with the example demo, you can change the size as you want.

 

That’s it, for now, this will be enough for you to start your first layout based on CSS grid.

Don’t forget to subscribe to cssparty newsletter to get the complete guide of CSS grid.

 

Want to keep up to date with the latest web industry knowledge?

Leave a reply:

Your email address will not be published.

Site Footer