CSS 带有无序列表的 Flexbox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32406364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:27:47  来源:igfitidea点击:

Flexbox with Unordered list

cssflexbox

提问by jrock2004

I am trying to learn flexbox and I really like it. I am trying play with dynamic widths and when I do it with divs it works. If I try to do it with li, it does not work as well. My code is up on codepen.

我正在尝试学习 flexbox,我真的很喜欢它。我正在尝试使用动态宽度,当我使用 div 时它可以工作。如果我尝试用 li 来做,它也不会奏效。我的代码在codepen 上

div.example
  ul
    li
      | 1
    li
      | 2
    li
      | 3
    li
      | 4
    li
      | 5
    li
      | 6

div.container
  div.col
    | 1
  div.col
    | 2
  div.col
    | 3
  div.col
    | 4
  div.col
    | 5
  div.col
    | 6

SASS Code

SASS代码

.container {
  border: 1px solid #000;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 50%;

  .col {
    width: calc(100% / 3);
    height: 120px;
    text-align: center;
  }
}

.example {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 50%;
  border: 1px solid #000;
  margin: 1em 0;

  ul {
    width: 100%;
    padding-left: 0;
  }

  li {
    list-style: none;
    display: inline-block;
    width: calc(100% / 3);
    height: 120px;
    text-align: center;
  }
}

回答by cocoa

You need to apply the flex properties to the <ul>

您需要将 flex 属性应用到 <ul>

ul {
  display: flex;
  flex-direction: row; <-- not needed as this is the default behavior
  flex-wrap: wrap;
}

Putting the properties on the <div>tells it to display the <ul>in flex, not <li>.

将属性放在<div>告诉它显示<ul>in flex,而不是<li>.

回答by Terry

Based on your markup, note that the <li>elements are the child of <ul>, not the .exampledivision element.

根据您的标记,请注意<li>元素是 的子元素<ul>,而不是.example除法元素。

<div class="example">
  <ul>
    <li>1</li>
  </ul>
</div>

Since the immediate parent of the <li>elements are <ul>, use the flexproperties on the <ul>that is wrapping around the multiple <li>elements, instead of the outer <div>element:

由于的直接父<li>元素<ul>,使用flex上的属性<ul>被缠绕在多个<li>元素,而不是外<div>元件:

.example {
  width: 50%;
  border: 1px solid #000;
  margin: 1em 0;

  ul {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 100%;
    padding-left: 0;
  }

  li {
    list-style: none;
    display: inline-block;
    width: calc(100% / 3);
    height: 120px;
    text-align: center;
  }
}

http://codepen.io/anon/pen/NGPBbg

http://codepen.io/anon/pen/NGPBbg