DEV Community

Cover image for Solving Dynamic Layout With CSS Grid
Vijay
Vijay

Posted on

Solving Dynamic Layout With CSS Grid

Today, I had a requirement to render a list of items in two columns.

Interestingly, 2 of the items need to use both columns.

First, I tried to use Flexbox, and then I thought, let's use Grid.

To test it out, I created a simple HTML structure for grid layout.

Here it is:

<div class="grid-container">
    <div class="grid-item">1</div>
    <div class="grid-item">2</div>
    <div class="grid-item">3</div>
    <div class="grid-item">4</div>
    <div class="grid-item">5</div>
    <div class="grid-item">6</div>
    <div class="grid-item span-both">7</div>
    <div class="grid-item span-both">8</div>
</div>

Enter fullscreen mode Exit fullscreen mode

In this structure, I created a grid container with 8 items. I needed to span the 7th and 8th items to use both columns. So I have added one more class on it span-both.

And then I added below CSS code to make it work.

.grid-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* Two columns */
    gap: 10px; /* Space between items */
}

.grid-item {
    background-color: lightblue;
    padding: 20px;
    text-align: center;
}

.span-both {
    grid-column: 1 / -1; /* Span both columns */
}

Enter fullscreen mode Exit fullscreen mode

You might be thinking, 'How does that work?'

So here is my explanation:

  • Grid Container: The display: grid; property activates the grid layout. I used grid-template-columns: repeat(2, 1fr); to create two equal columns.
  • Styling Grid Items: I gave each grid item a light blue background and some padding for better visibility.
  • Spanning Columns: The .span-both class uses grid-column: 1 / -1;, allowing the 7th and 8th items to stretch across both columns, making them stand out.

That's it for today.

Feel free to experiment with different layouts, colors, and spacing to create a grid that suits your needs.

Or let me know if you are having any issues.

Happy coding!

Top comments (0)