弹性方向栏无法正常工作

时间:2019-05-23 20:52:42

标签: html css flexbox

我有以下标记:

<div class="container">
  <div class="logo"></div>
  <div class="search"></div>
  <div class="button"></div>
</div>

CSS(台式机):

.container {
  display: flex;
}

在桌面视图上,它们连续显示,如下所示:

enter image description here

但在移动设备视图上,我希望它们重新排序:

enter image description here

我尝试了以下样式:

// here's media query for mobile devices
.container {
  flex-direction: column;
  flex-wrap: wrap;
  align-items: stretch // so my items would be filling width
}

.logo {
  order: 1;
  flex: 1 0 50%;
}

.search {
  order: 2;
  flex: 0 1 100%;
}

.button {
  order: 1;
  flex: 1 0 50%;
}

但是我的结果是:

enter image description here

使用Flexbox还能做到吗?

3 个答案:

答案 0 :(得分:2)

您需要使用flex-grow(了解flexbox的宝贵资源:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

HTML

<div class="container">
  <div class="logo">Logo</div>
  <div class="search">Search</div>
  <div class="button">Button</div>
</div>

CSS

.container {
  background-color: #ccc;
  display: flex;
  width: 300px;
  flex-wrap: wrap;
  text-align: center;
}

.container > div {
  background-color: grey;
  margin: 10px 20px;
  padding: 10px 20px;
}

.logo {
  order: 1;
  flex-grow: 1;
}

.search {
  order: 2;
  flex-grow: 2;
}

.button {
  order: 1;
  flex-grow: 1;
}

答案 1 :(得分:2)

您应该查看“ flex-grow”,如果需要,它可以使flex项增长,以便占用其容器中可用的空间。如果所有flex-item(在您的情况下:.logo,.search,.button)的flex-grow值为1,则.container中的剩余空间将平均分配给它的子项。

此外,您应该使用

    flex-direction: row;

如果您想让它们水平拉伸

查看此小提琴以供参考! https://jsfiddle.net/hgs5w19y/2/

答案 2 :(得分:0)

不需要方向,也不需要太多规则,只需设置一个断点并重置.search行为

.container {
  display: flex;
  flex-wrap: wrap;
}

.container>div {
  flex: 1;
}

div.search {
  order: 1;
  flex-basis: 100%;
}

@media screen and (min-width:731px) {
  div.search {
    order: 0;
    flex: 1
  }
}


/* demo purpose */

.container {
  background: gray;
}

.container>div {
  padding: 1em;
  margin: 1em;
  background: lightgray;
}

.container>div:before {
  content: attr(class);
  color: black;
}
<div class="container">
  <div class="logo"></div>
  <div class="search"></div>
  <div class="button"></div>
</div>

断点值将更新为您的断点值(此处将演示设置为731),以查看行为,在整个页面中运行摘要,或使用演示https://codepen.io/gc-nomade/pen/mYXZdY