CSS Grids

Introduction

In this blog, we will see about grids in CSS along with an example.

CSS Grids

CSS grids displays the elements in rows and columns. CSS flex property allows us to display only in one direction either row-wise or column-wise. But with the help of grids we can display it in whatever direction we need i.e,.. both row and column. 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GRID</title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
        }
    </style>
</head>

<body>
    <div class="container">
        <p>one</p>
        <p>two</p>
        <p>three</p>
        <p>four</p>
        <p>five</p>
    </div>
</body>

</html>

It provides the following output,

As you can see we have applied grid display property,

.container {
    display: grid;
    grid - template - columns: 1 fr 1 fr 1 fr;
}

I have given grid template columns "1fr" 3 times indicating that it should have 3 columns 

We can rewrite this code as,

.container {
    display: grid;
    grid - template - columns: repeat(3, 1 fr);
}

I have given repeat 3 to repeat the condition 1fr 3 times. Both provide the same output.

To specify gaps between grid columns we use grid-column-gap and to have space between grid rows we use grid-template-rows.

To declare same gap for both column and rows we can simply give grid-gap.

Eg

grid-column-gap: 20px;
grid-row-gap: 20px;

The above code can be written as,

grid-gap: 20px;

Both provide the same output. (fr is a functional unit).

If the contents of the grid are irregular, we can use grid-auto-rows property. 

Eg

{
    grid-auto-rows: minmax(100px, auto);
}

It sets a minimum of 100px to all rows and if the contents of row/column are large & invisible /hidden then 'auto' will change the row width as per the content.

Summary

We will see more about grids on upcoming articles. I hope this content will be helpful for beginners learning CSS and people struggling with CSS. That's it for today friends. 

Thank you!