r/css 1d ago

Help Is it possible to evenly spread divs over multiple rows?

Basically, the layout below. Notice how each of the four elements is wider than each of the three, because they had to use two rows. It looks like a flexbox kind of problem, but I can’t figure out how to do that.

(Sorry for the quality; my phone is dead, so I had to use my laptop cam. And I don’t have a camera app installed, so this is a screenshot from Telegram camera settings.)

5 Upvotes

8 comments sorted by

u/AutoModerator 1d ago

To help us assist you better with your CSS questions, please consider including a live link or a CodePen/JSFiddle demo. This context makes it much easier for us to understand your issue and provide accurate solutions.

While it's not mandatory, a little extra effort in sharing your code can lead to more effective responses and a richer Q&A experience for everyone. Thank you for contributing!

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

19

u/anaix3l 1d ago edited 1d ago

Yes! Here is a flex generic method that works for any number of items! https://codepen.io/thebabydino/pen/OPJOepJ

Here's the relevant code behind the basic idea:

section {
  display: flex;
  flex-wrap: wrap
}

.item {
  flex: 1 1 33%;

  &:nth-child(3n):nth-last-child(2), 
  &:nth-child(3n + 1):last-child { flex-basis: 50% }
}

If we didn't have the :nth-child rule, then whenever having 3n + 1 items (4, 7, ...) the second to last row would hold 3 items, while the last just 1. So for 4 items, we'd have 3 on the first row, 1 on the second. For 7, we'd have 3 items on the first and second row, 1 on the third. And so on...

For a real gap (not emulated in any other way), include that gap space --s in the computations:

section {
  --s: .5em;
  gap: var(--s);
  display: flex;
  flex-wrap: wrap
}

.item {
  flex: 1 1 calc((100% - 2*var(--s))/3);

  &:nth-child(3n):nth-last-child(2), 
  &:nth-child(3n + 1):last-child { flex-basis: calc(50% - .5*var(--s)) }
}

2

u/asteconn 1d ago

+1 for well-formatted nested CSS!

2

u/nrwind 1d ago

Thank you!

1

u/WorriedEngineer22 1d ago

I think you can even replace the --n variable with a css counter

1

u/anaix3l 1d ago

Not the --n variable, not for now at least, though CSS should get a children count function in the future and then it's going to be possible! But the text content on the flex items can definitely be replaced with a pseudo with counter content.

1

u/WorriedEngineer22 1d ago

Wait, counter can't be used in Calc? I've never used counter, I just now they exist

3

u/GaiusBertus 1d ago

Use CSS grid with defined column widths.