flexbox child padding breaks width distribution [duplicate]

4 days ago 9
ARTICLE AD BOX

Not sure I follow the accepted answer. The nested flex container doesn't seem to be relevant to the problem. If you run the example without display: flex; on .Item, the problem persists.

The problem here seems to be that flex-grow only calculates the available space that it can take after factoring in the cumulative horizontal padding.

Let's assume the top level flex container is 300px wide.

1st row's available space: 300px - 30px padding = 270px

The flex items in this row have flex-grows of 1, 1, and 2, for a total of 4 units. 270 / 4 = 67.5px. The content boxes of 1A and 1B are thus 67.5px each, the content box of 1C is 135px.

2nd row's available space: 300px - 20px padding = 280px

We have flex-grows of 1 for both 2A and 2B in this row. 280 / 2 = 140px.

So 1A and 1B would have a content box of 67.5px + 10px horizontal padding, making their total width 77.5px each.

2A would have a content box of 140px + 10px horizontal padding, making its total width 150px.

77.5px + 77.5px ≠ 150px. In other words, 1A + 1B ≠ 2A, and that's why they aren't lining up.

The accepted answer does solve the problem, but CSS grid has become well supported since that answer was submitted, and is the more idiomatic approach nowadays for this problem.

.Row{ display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; } .Item:nth-child(n + 3) { grid-column: span 2; } .Item > div{ background:#7ae; } <div class="Row"> <div class="Item"> <div>1A</div> </div> <div class="Item"> <div>1B</div> </div> <div class="Item"> <div>1C</div> </div> <div class="Item"> <div>2A</div> </div> <div class="Item"> <div>2B</div> </div> </div>
Read Entire Article