As shown on the picture, there are 4 small elements (green) and 1 large one (red). I want them to be placed in such way as shown, depending on the window’s aspect ratio. I have tried to do it with CSS but with no success (I have little experience with it). Can it be done with CSS? Or some java script is needed?
>Solution :
As already said, you can easily use CSS-Grid here.
Wrap the elements within a container that has display: grid and uses a 2-column layout by using grid-template-columns: repeat(2, 1fr).
To make the red box larger as provided in the image, you have to assign grid-column: span 4; grid-row: span 4; to it.
Changing the layout can be done using media queries. You simply have to change to a 3-column layout and changing the placement to grid-auto-flow: column dense.
.d-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-auto-rows: 1fr;
grid-gap: 1em;
}
@media only screen and (width > 480px) {
.d-grid {
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: column dense;
}
}
.red {
grid-column: span 2;
grid-row: span 4;
}
/* for demo purpose only */
.green {
min-height: 20vh;
background-color: green;
}
.red {
background-color: red;
}
<div class="d-grid">
<div class="green"></div>
<div class="green"></div>
<div class="green"></div>
<div class="green"></div>
<div class="red"></div>
</div>