I'm trying to design a layout like this:
When there are 3 grid items I want them to be stacked like in the first picture. When there are 2 I want them to be stacked like in the second picture, and when there is only 1 item it should take up all available space. This should be dynamic and automatic.
I got pretty close using CSS grid, but unfortunately when it's just the purple item it doesn't work. Is there any way to achieve this? (please don't suggest flexbox or other solutions. I am aware and need this exact behavior)
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
padding: 10px;
border: 2px solid black;
margin-bottom: 10px;
}
.grid div {
background: blue;
height: 50px;
}
.grid > div:nth-child(1){
grid-column: 1 / 2; /* can I change this line and have all 3 examples work? */
background: #952662;
}
.grid > div:nth-child(2){
grid-column: 2 / -1;
background: #263195;
}
.grid > div:nth-child(3){
grid-column: 1 / -1;
background: #E49F17;
}
Works
<div class="grid"><div></div><div></div><div></div></div>
Works
<div class="grid"><div></div><div></div></div>
Doesn't work
<div class="grid"><div></div></div>