Is it possible in pure CSS to lay out list elements to arbitrary number of columns, preserving the left-to-right order, as on this example?
Yes, it should be theoretically possible.
Since you want the flex items arranged in columns,
#flex-container { flex-flow: column wrap; }
But then the order of the elements would be preserved vertically (in columns). Since you want horizontally, they must be reordered:
#flex-container > :nth-child(4n - 2) { order: 1; } #flex-container > :nth-child(4n - 1) { order: 2; } #flex-container > :nth-child(4n - 0) { order: 3; }
And then we must force column breaks.
According to 10. Fragmenting Flex Layout and CSS Fragmentation, line breaks can be forced with break-before:
break-before
#flex-container > :nth-child(-n + 4) { page-break-before: always; /* CSS 2.1 syntax */ break-before: always; /* New syntax */ }
However, forced breaks in flexbox are not widely implemented yet. It works on Firefox, though.
#flex-container { display: flex; flex-flow: column wrap; } #flex-container > :nth-child(4n - 2) { order: 1; } #flex-container > :nth-child(4n - 1) { order: 2; } #flex-container > :nth-child(4n - 0) { order: 3; } #flex-container > :nth-child(-n + 4) { page-break-before: always; /* Old syntax */ break-before: always; /* New syntax */ border-top: 1px solid; }
<div id="flex-container"> <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> <span>6</span> <span>7</span> <span>8</span> <span>9</span> <span>10</span> </div>
2.1m questions
2.1m answers
60 comments
57.0k users