CSS转发内容流

ecc*_*ecc 11 css css-selectors css3 flexbox

有没有办法使用flex或其他技术在CSS中定义内容流,这样内容"zig zags"或以这种方式四处走动:

 -----------------
|A > B > C > D > E|
|J < I < H < G < F|
 -----------------

 ---
|A H|
|B G|
|C F|
|D E|
 ---
Run Code Online (Sandbox Code Playgroud)

假设总有2列或行.我可以将项目拆分为2并在它们周围创建2个包装项目,但我希望它更具动态性.

基本上,如何让第一行向右流动,第二行向左流动?

Sal*_*n A 2

以下解决方案不使用 JavaScript 并且具有一定的可扩展性。我使用display: flex这样我就可以使用该order财产。

基本思想是分配order: 1给最后一项、order: 2倒数第二项等等。项目的前半部分 hasorder: -1和伪元素havingorder: 0用作分隔符。棘手的部分是你要找出项目的“前半部分”:

.demo {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background: #EEE;
}
.demo > * {
  margin: .5em;
  width: 4em;
  height: 4em;
  background: #0CF;
}

/*
 * the example work for a list of 20 elements
 * for additional elements extend the repeating selectors
 */

/* all items ordered backwards */

.demo > :nth-last-child(1)  { order: 1; }
.demo > :nth-last-child(2)  { order: 2; }
.demo > :nth-last-child(3)  { order: 3; }
.demo > :nth-last-child(4)  { order: 4; }
.demo > :nth-last-child(5)  { order: 5; }
.demo > :nth-last-child(6)  { order: 6; }
.demo > :nth-last-child(7)  { order: 7; }
.demo > :nth-last-child(8)  { order: 8; }
.demo > :nth-last-child(9)  { order: 9; }
.demo > :nth-last-child(10) { order: 10; }

/* first half items are source ordered */

.demo> :nth-child(-n+0):nth-last-child(n+1),
.demo> :nth-child(-n+1):nth-last-child(n+2),
.demo> :nth-child(-n+2):nth-last-child(n+3),
.demo> :nth-child(-n+3):nth-last-child(n+4),
.demo> :nth-child(-n+4):nth-last-child(n+5),
.demo> :nth-child(-n+5):nth-last-child(n+6),
.demo> :nth-child(-n+6):nth-last-child(n+7),
.demo> :nth-child(-n+7):nth-last-child(n+8),
.demo> :nth-child(-n+8):nth-last-child(n+9),
.demo> :nth-child(-n+9):nth-last-child(n+10),
.demo> :nth-child(-n+10):nth-last-child(n+11) {
  order: -1;
}

/* the separator uses flex-basis trick and ordered between the two halves */

.demo::after {
  content: "";
  flex-basis: 100%;
  order: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="demo">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>
Run Code Online (Sandbox Code Playgroud)

对于两列布局,flex-direction: column; height: 25em在父级上指定(高度必须固定)。

  • 这个解决方案太疯狂了,我喜欢它 (2认同)