【问题标题】:How can I put elements underneath each other in flex display?如何在弹性显示中将元素放在彼此下方?
【发布时间】:2018-04-09 18:09:49
【问题描述】:

这是我的代码:

.menu_box {
  background-color: whitesmoke;
  margin: auto;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border-radius: 3px;
  width: 100vh;
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.menu_box_body {
  flex-grow: 1;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width:100%;
}

.menu_box_header {
  height: 45px;
  background-color: #f1f1f1;
  border-bottom: 1px solid #e1e1e1;
  position: relative;
  margin-bottom: 10px;
  width: 100%;
}

.menu_options {
  border: 1px solid #e1e1e1;
  display:flex;
  align-items:center;
  justify-content:center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="menu_box">
  <div class="menu_box_header">
  </div>
  <div class="menu_box_body">
    <div class="menu_options col-xs-6"><div>{icon}</div><h3>part1</h3></div>
    <div class="menu_options col-xs-6"><div>{icon}</div><h3>part2</h3></div>
    <div class="menu_options col-xs-6"><div>{icon}</div><h3>part3</h3></div>
    <div class="menu_options col-xs-6"><div>{icon}</div><h3>part4</h3></div>
  </div>
</div>

我想将{icon} 放在partN 的顶部(不是每个partN 的旁边)。我怎样才能做到这一点?如您所知,&lt;div&gt;&lt;h3&gt; 都有 block 显示。但我真的不知道他们为什么挨着。无论如何,我怎样才能把它们放在一起呢?

【问题讨论】:

  • 您需要在.menu_options 上声明flex-direction: column;。由于.menu_options 已设置为display: flex;,因此无论您为这些子元素设置的显示类型如何,嵌套元素都根据flexbox 模型 进行布局。所以换句话说,你仍然需要定义 flex 容器的子元素的 direction

标签: javascript jquery html css flexbox


【解决方案1】:

如果将 .menu_box_body css 替换为以下两行

flex-direction: row;
flex-wrap: wrap;

下面两行

flex-direction: column;
align-items:center;

你会得到结果。最终的 CSS 将是:

.menu_box_body {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items:center;
  width:100%;
}

【讨论】:

    【解决方案2】:

    您已将 display flex 添加到 .menu_options 元素,该元素引用单元格。这就是为什么元素不像块那样充当块的原因,如果您在那里删除 display flex,它们将堆叠在一起。

    如果您仍想在此处使用 display:flex(例如将内容居中),您可以添加 flex-direction: column - 这也将使它们彼此重叠。

    【讨论】:

    • 如果我删除display:flex;,那么项目将不再居中(垂直)。
    • 我已经扩展了我的答案来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2021-03-09
    • 2015-08-14
    相关资源
    最近更新 更多