Reputation: 847
I would like to create a 3x3 grid that shrinks boxes one under the other when on smaller screen. Boxes should be always the perfect square.
Also, the last two boxes (8 + 9) should be only one longer rectangle on larger screen, but take the same space as now. Is CSS grid a way to go here? Here's what I got:
body {
background: lightblue;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-gap: 20px;
}
.grid div {
width: 100%;
height: 100%;
background: white;
padding: .5em;
}
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div>join</div>
<div>us</div>
</div>
Upvotes: 2
Views: 6890
Reputation: 331
I wanted to make it a simple 3x3 grid, and also that code doesn't work properly when you resize to mobile. Only a few of the squares showed when I tried it.
I removed the .grid div:last-child:nth-child(3n - 1)
from the CSS, and added an extra element.
Got the working and tested grid after that.
.grid {
background: lightblue;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-gap: 20px;
}
.grid div {
width: 100%;
height: 0%;
padding-bottom: 100%;
background: white;
}
@media (max-width: 400px) {
.grid {
grid-template-columns: 1fr;
}
<div class="grid">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
Upvotes: 0
Reputation: 1460
You can do something like this -
body {
background: lightblue;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-gap: 20px;
}
.grid div {
width: 100%;
height: 0%;
padding-bottom: 100%;
background: white;
}
.grid div:last-child:nth-child(3n - 1) {
grid-column: span 2;
height: auto;
padding-bottom: 0;
}
@media (max-width: 400px) {
.grid {
grid-template-columns: 1fr;
}
}
<div class="grid">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div>join us</div>
</div>
...and then add media query to make it responsive.
Edit:
What I did is -
.grid div
to 0 and added padding-bottom: 100%
to make it a perfect square..grid div:last-child:nth-child(3n - 1)
to target the last child and make it fill the rest of the grid.Edit 2: Added media query.
Upvotes: 2