如何消除flex-wrap创建的额外间距

4

我正在尝试使用flex布局制作下拉菜单。当菜单项超过6个时,每个菜单项的宽度将会是50%;当不足6个时,每个菜单项的宽度将会是100%。

The parent container should have a maximum width and should shrink if they are not many items.
So I got that working, but I cannot seem to get rid of the extra 'space' on the right of the 100% wide items. Does anyone have an idea to solve this? The extra space grows larger if the items have much text in it, making it rather unnecessary big.

ul {
  background: red;
  display: inline-flex;
  flex-wrap: wrap;
  flex-direction: row;
  max-width: 400px;
  margin: 0;
  padding: 10px;
  list-style: none;
  min-width: 0;
  align-content: start;
}

li {
  flex-basis: 50%;
  margin: 0;
  padding: 0;
}


/* If there are less than 6 */
li:nth-last-child(-n+6):first-child,
li:nth-last-child(-n+6):first-child ~ li {
  flex-basis: 100%;
  min-width: 0px;
}
<ul>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
</ul>

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>

1个回答

2

我猜用弹性盒子布局可能会很棘手,但你可以使用浮动来轻松实现相同的效果,而不会有额外的空白:

ul {
  background: red;
  display: inline-block;
  vertical-align: top;
  overflow: auto;
  max-width: 400px;
  margin: 0;
  padding: 10px;
  list-style: none;
}

li {
  float: left;
  padding: 0 5px;
}

li:nth-child(odd) {
  clear: left;
}

/* If there are less than 6 */
li:nth-last-child(-n+6):first-child,
li:nth-last-child(-n+6):first-child ~ li {
  float: none;
}
<ul>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
</ul>

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>

或者使用CSS网格布局:

ul {
  background: red;
  display: inline-grid;
  column-gap:5px;
  max-width: 400px;
  margin: 0;
  padding: 10px;
  list-style: none;
}

li:nth-child(2) {
  grid-column:2;
}

/* If there are less than 6 */
li:nth-last-child(-n+6):first-child ~ :nth-child(2) {
  grid-column:initial;
}
<ul>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
  <li>hello</li>
</ul>

<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>


这些天我忙于flexbox,甚至都没想过浮动!谢谢,如果我无法使用flexbox使其正常工作,我一定会使用它。 - CaptainFurball
@CaptainFurball 我还添加了一个CSS网格解决方案,如果你想处理间隙可能会更容易。 - Temani Afif
谢谢!我可能会选择浮点数解决方案(为了兼容性),但是拥有一个网格示例也很好。 - CaptainFurball

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接