0

Assuming this HTML

<div class="boxes">
    <div class="box">Some</div>
    <div class="box">Something</div>
    <div class="box">A</div>
    <div class="box">Something longer</div>
    <div class="box">B</div>
    <div class="box">Lemons</div>
</div>

I was presented with a rather stranger design, where there is:

  • fixed number of "boxes" on each row - 3 to be specific
  • same space between boxes on the line (let's say 15px)
  • they are spread while keeping their original ratio among themselves (the imaginary "left space" on the row is distributed as their width but based on their oririnal size ratio - not equaly

If there would not be the ratio issue, CSS would be

.boxes {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;  
}
.boxes .box {
    background: #006600;
    flex-basis: calc(33.33% - 15px);
    padding: 12px 10px;
    text-align: center;
}

Problem with this solution is that the boxes always take 1/3 becuse of the flex-basis, if I don't set the flex-basis, there are more boxes than 3 per row.

Basically I need something like

.boxes {
    display: flex;
    flex-wrap: wrap;  
}
.boxes .box {
    flex-grow: 1;
}

But with a set number of items per row - is that even possilbe?

EDIT: Just to clarify, I am looking for a way how to do this without altering the HTML, if you are able to alter the HTML you can simply spread it with flex-grow: 1 and put a breaking element after each N of items or wrap each N of items in a separate row (flex container).

jave.web
  • 13,880
  • 12
  • 91
  • 125
  • 1
    use CSS grid for this – Temani Afif Feb 13 '21 at 15:14
  • @TemaniAfif is that achievable using flexbox layout though? The backwards browser compatibility is slightly better there – jave.web Feb 13 '21 at 15:27
  • @TemaniAfif also could provide a solution/hint on how to do this with CSS grid? – jave.web Feb 13 '21 at 15:30
  • what do you mean by *ratio* ? technically, your elements don't have any ratio since they are a div elements (images have ratio) – Temani Afif Feb 13 '21 at 18:22
  • @TemaniAfif images have ratio between their width and height, I am talking about ratio between the widths of each element on the row - since each element has a content of a different length, therefore a different "starting width" - see what happens if you just use flex-grow: 1 on 3 elements with a different-length-content, sidenote: **all elements** have a starting width:height ratio depending on their content or pre-set dimensions, that is however not the ratio I am talking about here. – jave.web Feb 14 '21 at 10:08

0 Answers0