Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

css - How to display list items as columns preserving the left-to-right order?

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?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

    #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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...