How to make rows in a grid stack without grid-template-row?

346 views Asked by At

I'm trying to make .item-1 and .item-2 stack nicely on top of each other in a grid, just like in this snippet:

.grid {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: auto 1fr;
}

.item {
    padding: 10px;
    border: 1px solid black;
}

.item-1 {
    grid-column: 1 / 3;
}

.item-2 {
    grid-column: 1 / 3;
}

.item-3 {
    grid-column: 3 / 7;
    grid-row: 1 / 3;
    
    padding: 80px 20px;
}
<div class="grid">
    <div class="item item-1">
        item-1
    </div>
    
    <div class="item item-2">
        item-2
    </div>
    
    <div class="item item-3">
        item-3
    </div>
</div>

This is a simplified example, and the implementation I'm stuck on has more rows of items in different places.
For example: large item first, or no large item at all.

Which is why grid-template-rows seems to be off the table, and I cannot find a way to stack them nicely without.

I've tried many different things, from grid-auto-rows to the various grid-* and align-*, to height and margins set to auto and fit-content, without success.

Here's the same snippet without grid-template-rows, where you can see the default behavior of .item-1 and .item-2 being separated / getting the same height:

.grid {
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(6, 1fr);
}

.item {
    padding: 10px;
    border: 1px solid black;
}

.item-1 {
    grid-column: 1 / 3;
}

.item-2 {
    grid-column: 1 / 3;
}

.item-3 {
    grid-column: 3 / 7;
    grid-row: 1 / 3;
    
    padding: 80px 20px;
}
<div class="grid">
    <div class="item item-1">
        item-1
    </div>
    
    <div class="item item-2">
        item-2
    </div>
    
    <div class="item item-3">
        item-3
    </div>
</div>

Here's an image of the snippets, showing the desired layout: enter image description here

2

There are 2 answers

0
Mohsen007 On

Try this

.grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 10px;
}

.item {
    border: 1px solid #000;
    padding: 10px;
}

.box1 {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.item2 {
    flex: 1;
}

.item3 {
    padding: 80px 20px;
}
<div class="grid" >
    <div class="box1">
        <div class="item" >item 1</div>
        <div class="item item2" >item 2</div>
    </div>
    <div class="item item3" >item 3</div>
</div>

0
Foramkumar Patel On

.grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
    gap: 10px;
}

.item {
    border: 1px solid #000;
    padding: 10px;
}

.box1 {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.item1 {
    flex: 1;
}

.item2 {
    flex: 1;
}

.item3 {
    padding: 80px 20px;
}
<div class="grid" >
    <div class="box1">
        <div class="item item1" >item 1</div>
        <div class="item item2" >item 2</div>
    </div>
    <div class="item item3" >item 3</div>
</div>