Shorthand way to achieve this grid?

Hello 👋 I'm trying to make a grid that alternates in items per row between 4 and 5 items. Is there a shorter way to do this without having to name each area? This is what I have so far: https://jsfiddle.net/bnamep5w/ I've also attached the effect I'm going for Thanks!
Edit fiddle - JSFiddle - Code Playground
Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor.
4 Replies
MarkBoots
MarkBoots•3y ago
don't know exactly what you want to achieve, but there is a simple hack to do this. a 9 column grid, every grid item gets an empty before element and you set the item to display contents so that both will be childs of the grid. But, you will lose the ability to style the individual grid cells (not necessary in your example)
<div class="grid">
<div>💡</div>
<div>💡</div>
<div>💡</div>
<!--- more -->
</grid>
<div class="grid">
<div>💡</div>
<div>💡</div>
<div>💡</div>
<!--- more -->
</grid>
.grid{
display: grid;
grid-template-columns: repeat(9,1fr);
place-items: center;
}
.grid > div { display: contents }
.grid > div::before { content: "" } /* this will be the empty cells */
.grid{
display: grid;
grid-template-columns: repeat(9,1fr);
place-items: center;
}
.grid > div { display: contents }
.grid > div::before { content: "" } /* this will be the empty cells */
Nick 🚀
Nick 🚀OP•3y ago
That's great! Thank you @MarkBoots
Joao
Joao•3y ago
Nice trick, I like it. Another option that I don't remember who suggested, but was in this Discord server, is to change the flow of the grid and use the :nth-child(2n) selector to target every other grid item. This way you can apply some margin or other styling accordingly:
.grid {
display: grid;
grid-auto-flow: column;
grid-template-rows: repeat(4, 1fr);
}

.grid div {
font-size: 3rem;
}

.grid div:nth-child(2n) {
margin-left: 50%;
}
.grid {
display: grid;
grid-auto-flow: column;
grid-template-rows: repeat(4, 1fr);
}

.grid div {
font-size: 3rem;
}

.grid div:nth-child(2n) {
margin-left: 50%;
}
But it can't be resized very well, and works only when you know the exact number of rows, so not very suitable for a wallpaper effect
Joao
Joao•3y ago
Want results from more Discord servers?
Add your server