使一个弹性项占据整个列

时间:2016-12-07 12:49:57

标签: html css css3 flexbox html-lists

我在flex布局中有一个无序列表。我希望第一个li项目("主页"菜单链接)位于其自己的列中,如下所示:

enter image description here

我该怎么做?

由于语义原因,我不想打破第一个列表项并将其放在一个单独的div中。我希望它在HTML中的列表中。



* {
  outline: solid 1px grey;
}
ul {
  display: flex;
  flex-wrap: wrap;
  list-style-type: none;
  white-space: nowrap;
}

li {
  flex: 1;
}

ul > li:first-child {
  /* This item should be in its own column */
  color: green;
}

<ul>
  <li>
    First item and this is it
  </li>
  <li>
    Second item this is the sh*t
  </li>
  <li>
    Third after two to go
  </li>
  <li>
    Forth enabled flex is flow
  </li>
  <li>
    Fifth the rabbit digs a hole
  </li>
  <li>
    Sixth hole in the pork says "miew"
  </li>
</ul>
&#13;
&#13;
&#13;

http://codepen.io/rooeee/pen/ObZwER

1 个答案:

答案 0 :(得分:2)

在具有row wrap的Flex容器中,除非添加容器,否则无法实现此布局。我知道你不想改变HTML。

但是,如果您可以切换到column wrap并为容器定义高度,则可以通过为其提供flex-basis: 100%来使第一个链接占据整个列。这会强制后续项目进行换行。

revised codepen

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  list-style-type: none;
  white-space: nowrap;
  height: 100px;
}
li {
  flex: 0 0 50%;
}
ul > li:first-child {
  flex-basis: 100%;
  color: green;
}
* {
  outline: solid 1px grey;
  box-sizing: border-box;
}
<ul>
  <li>
    First item and this is it
  </li>
  <li>
    Second item this is the sh*t
  </li>
  <li>
    Third after two to go
  </li>
  <li>
    Forth enabled flex is flow
  </li>
  <li>
    Fifth the rabbit digs a hole
  </li>
  <li>
    Sixth hole in the pork says "miew"
  </li>
</ul>

ALSO ,如果你不想改变HTML的唯一理由是语义,你仍然可以在基于行的容器中构建布局,同时坚持干净,有效和语义的代码。换句话说,创建嵌套的flex容器很好。

revised codepen

ul {
  display: flex;
  list-style-type: none;
	white-space: nowrap;
}
ul:first-child > li:first-child {
  flex: 0 0 20%;
}
ul:first-child > li:nth-child(2) {
  flex: 0 0 80%;
}
ul:first-child > li:nth-child(2) ul {
  flex-wrap: wrap;
}
ul:first-child > li:nth-child(2) li {
  flex: 0 0 50%;
}
* {
  box-sizing: border-box;
  padding: 0;
  outline: solid 1px grey;
}
<ul><!-- primary flex container -->
  <li>First item and this is it</li><!-- flex item #1 -->
  <li><!-- flex item #2 -->
    <ul><!-- nested flex container -->
      <li>Second item this is the sh*t</li><!-- flex item -->
      <li>Third after two to go</li><!-- flex item -->
      <li>Forth enabled flex is flow</li><!-- flex item -->
      <li>Fifth the rabbit digs a hole</li><!-- flex item -->
      <li>Sixth hole in the pork says "miew</li><!-- flex item -->
    </ul><!-- END nested flex container -->
  </li><!-- END flex item #2 -->
</ul><!-- END primary flex container -->