FrontendPro

97Implement a responsive masonry layout using measured item heights

mediumAbout 45 minutesCodingreactlayoutmeasurementperformance

Problem

A Pinterest-style masonry grid places each item in the shortest column, so columns end up roughly equal in height even though items differ.

  1. getColumnCount(containerWidth, minColumnWidth, gap): the most columns that fit when each is at least minColumnWidth wide with gap between them (at least 1).
  2. computeLayout(heights, { columns, columnWidth, gap }): for items with the given heights, in order, return { positions: [{ x, y }], height }, placing each item at the top of the currently shortest column (the leftmost on ties). height is the tallest column (without a trailing gap).
  3. <Masonry items={items} minColumnWidth={200} gap={12} renderItem={(item) => …} />: render items absolutely positioned (transform: translate(x, y)), measure each item's real height after render, recompute the layout, and size the container to the layout height. Recompute when the container width changes.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

n columns need n * min + (n - 1) * gap pixels, so n = floor((width + gap) / (min + gap)), at least 1. The real column width is (width - (n - 1) * gap) / n.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever