Create Awesome Masonry Layout With CSS Grid

Usually In masonry layout items are laid out one after another in the inline direction. It’s almost similar to a grid layout, but the only difference is that in masonry layout without being sticky to a strict grid with gaps left by shorter items, items from the following rows move up to fill up the gaps.

There are some jQuery plugins available to create a masonry layout but today I’m going to show you how you can create this layout using few lines of code with a CSS grid.

Step 1: HTML Code

<!– Masonry layout Start –>

    <div class=”container”>

        <div class=”item-1″>

            <img src=”https://picsum.photos/300/600/?random”>

        </div>

        <div class=”item-2″>

            <img src=”https://picsum.photos/600/300/?random”>

        </div>

        <div class=”item-3″>

            <img src=”https://picsum.photos/200/200/?random”>

        </div>

        <div class=”item-4″>

            <img src=”https://picsum.photos/200/500/?random”>

        </div>

        <div class=”item-5″>

            <img src=”https://picsum.photos/200/400/?random”>

        </div>

        <div class=”item-6″>

            <img src=”https://picsum.photos/200/250/?random”>

        </div>

        <div class=”item-7″>

            <img src=”https://picsum.photos/200/100/?random”>

        </div>

        <div class=”item-8″>

            <img src=”https://picsum.photos/200/600/?random”>

        </div>

    </div>

    <!– Masonry layout End –>

 

Step 2: CSS Code

.container {

  max-width: 800px;

  padding: 1rem;

  margin: 0 auto;

  display: grid;

  grid-template-columns: repeat(4,1fr);

  grid-template-rows: 200px 200px 200px;

  grid-gap: 1rem;

}

img {

  object-fit: cover;

  width: 100%;

  height: 100%;

  border-radius: 10px;

}

.item-1 {

  grid-row: 1 / 3;

}

.item-3 {

  grid-column: 3 / 5;

 

.item-5 {

  grid-row: 2 / 4;

}

.item-8 {

  grid-column: 3 / 5;

}

 

Now save your code and refresh your browser to see the result.
Happy Coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *