如何使用'display:flex'在容器中包装列表项?

时间:2015-06-17 19:18:38

标签: html css flexbox

我正在使用灵活的盒子模块('display:flex'),无法获取我的列表项目。我有一些非常简单的HTML和CSS,但由于某种原因,列表项的行为不符合我的要求。

以下是我在Codepen上的工作:

<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.flex-item:nth-of-type(1) { flex-grow: 1; }
.flex-item:nth-of-type(2) { flex-grow: 1; }
.flex-item:nth-of-type(3) { flex-grow: 2; }
.flex-item:nth-of-type(4) { flex-grow: 1; }
.flex-item:nth-of-type(5) { flex-grow: 1; }

.flex-item {
  background: tomato;
  border: 3px solid rgba(0,0,0,.2);
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>

具体来说,目标是拥有两行内容。顶级将有项目'1','2'和'3',底部将有项目'4'和'5'。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

您可以强制换行在正确的位置插入足够宽的伪元素:

.flex-container::after {
  content: '';
  width: 100%; /* Force a line break */
}
.flex-item:nth-of-type(n + 3) {
  order: 1;    /* Place them after the ::after */
}

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;

  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.flex-item {
  background: tomato;
  border: 3px solid rgba(0,0,0,.2);
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
  flex: 1;
}
.flex-item:nth-of-type(3) {
  flex: 2;
}
.flex-item:nth-of-type(n + 3) {
  order: 1
}
.flex-container::after {
  content: '';
  width: 100%;
}
<ul class="flex-container">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
</ul>