I have a grid layout for a dashboard I am building. I am trying to achieve the following:
- Maintain aspect ratio of grid elements
- Ensure each grid row is filled/complete. This is the problem child in my case. I have seen multiple tutorials and answers on here where the rows may contain a leftover element in a new row as the width decreases. This creates a lot of empty space in the grid to the right of the isolated grid elements/incomplete row. I want the grid to shift to decrease columns to the next lowest divisible number result in complete rows. If the grid starts with a non divisible number (prime) it can only go to a single column for collapsing say 3 grid items collapses to 1 since its the highest divisor hence maintaining complete rows. Another example, 6 items would collapse to 3 columns of 2 then 2 columns of 3 then 1 column of 6.
I am curious if there is a pure CSS method for ensuring the row stays complete or if this will require javascript. Either answer will suffice but I will favor a pure css solution.
My code so far:
.grid-4-2-1 {
display: grid;
grid-template-areas: "grid-child-1 grid-child-2 grid-child-3 grid-child-4";
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-gap: 20px;
margin: 20px;
}
.grid-child {
position: relative;
align-items: center;
justify-content: space-between;
padding-top: 100%;
background-color: #fff;
position: relative;
}
.grid-child .grid-content {
position: absolute;
right: 0px;
top: 0px;
height: 100%;
width: 100%;
}
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (max-width: 768px) {
.grid-4-2-1 {
grid-template-areas: "grid-child-1 grid-child-2 grid-child-3 grid-child-4";
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-gap: 20px;
margin: 20px;
}
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 480px) {}
<div class="grid-4-2-1">
<grid-child-1 class="grid-child">
<div class="grid-content">Overview</div>
</grid-child-1>
<grid-child-2 class="grid-child">
<div class="grid-content">Overview</div>
</grid-child-2>
<grid-child-3 class="grid-child">
<div class="grid-content">Overview</div>
</grid-child-3>
<grid-child-4 class="grid-child">
<div class="grid-content">Overview</div>
</grid-child-4>
</div>