Tengo una lista de elementos de diferentes alturas y quiero distribuirlos de manera que se llene el ancho completo de la pantalla (pero no se desborde con una barra de desplazamiento horizontal):
¿Cómo puedo lograr esto a través de CSS? No puedo simplemente cambiar a flex-direction: row , ya que habría grandes espacios entre las filas debido a las diferentes alturas de los elementos.
Aquí está mi intento de pirateo a través de JS: https://codesandbox.io/s/dreamy-joliot-9n3woy?file=/src/App.js
import React, { useState, useEffect } from "react"; const BOX_WIDTH = 200; const boxHeights = [...Array(500)].map(() => Math.random() * 100); export default function App() { const ref = React.useRef(); const [originalHeight, setOriginalHeight] = useState(); useEffect(() => { if (!originalHeight && ref.current?.clientHeight) { setOriginalHeight(ref.current?.clientHeight); } }, [originalHeight, ref.current?.clientHeight]); const [height, setHeight] = useState(); useEffect(() => { if (originalHeight && ref.current?.clientWidth) { setHeight( originalHeight / Math.floor(ref.current?.clientWidth / BOX_WIDTH) / 0.9 ); } }, [ref.current?.clientWidth, originalHeight]); return ( <> <div ref={ref} style={{ display: "flex", flexDirection: "column", flexWrap: "wrap", ...(height && { height }) }} > {[...Array(500)].map((_, i) => ( <div style={{ border: "solid", width: BOX_WIDTH, height: boxHeights[i], margin: "10px" }} /> ))} </div> </> ); }