使弹性项目彼此相邻

时间:2017-11-02 22:29:09

标签: html css css3 flexbox media-queries

我有10个div:2个隐藏,8个堆叠在一起。

使用媒体查询,在调整屏幕大小时,我可以显示2个隐藏的div。

所以,现在我底部有4个红色div,但我希望它们成对出现 - 2行,2个红色div,彼此相邻。

enter image description here

我该怎么做?



html {
  font-size: 20px;
}

.box {
  color: white;
  font-size: 100px;
  text-align: center;
  text-shadow: 4px 4px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  Margin: 5px;
  /*  width: calc(33.33% - 10px);*/
}


/* Flexbox code starts here */

.container {
  display: flex;
  /*Must!!!! on the container, in order to turn it to flex*/
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: center;
}


/* Colors for each box */

.blue {
  background: blue;
}

.orange {
  background: Orange;
  height: 300px;
}

.green {
  background: green;
}

.red {
  background: red;
  height: 170px;
}

.hide-reds {
  display: none;
}


/*Media Queries for Different Screen Sizes*/

@media all and (min-width: 800px) {
  .red {
    display: block;
  }
}

<div class="container">
  <div class="box blue">Blue</div>
  <div class="box blue">Blue</div>
  <div class="box orange">Orange</div>
  <div class="box green">Green</div>
  <div class="box green">Green</div>
  <div class="box green">Green</div>
  <div class="box red">Red</div>
  <div class="box red">Red</div>
  <div class="box red hide-reds">Red</div>
  <div class="box red hide-reds">Red</div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的容器有flex-direction: column。您的布局有一列。但是,没有办法在一列中将Flex项目彼此相邻包装。 Flexbox doesn't work that way.

但是,您的布局可以与flex-direction: rowflex-wrap: wrap一起使用。通过给每个项目width: 100%,每个项目强制下一个项目到下一行。这会创建一列堆叠的项目。然后,给出最后四项width: 50%,这样两条就适合每一行。

&#13;
&#13;
.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  flex: 0 0 100%;
}

.red {
  flex: 1 0 100%;
  background: red;
  height: 170px;
}

.hide-reds {
  display: none;
}

@media all and (min-width: 800px) {
  .red {
    flex-basis: 40%; /* see note below */
    display: block;
  }
}


/* not relevant to the problem */
.blue {
  background: blue;
}

.orange {
  background: Orange;
  height: 300px;
}

.green {
  background: green;
}

html {
  font-size: 20px;
}

.box {
  color: white;
  font-size: 100px;
  text-align: center;
  text-shadow: 4px 4px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  margin: 5px;
}
&#13;
<div class="container">
  <div class="box blue">Blue</div>
  <div class="box blue">Blue</div>
  <div class="box orange">Orange</div>
  <div class="box green">Green</div>
  <div class="box green">Green</div>
  <div class="box green">Green</div>
  <div class="box red">Red</div>
  <div class="box red">Red</div>
  <div class="box red hide-reds">Red</div>
  <div class="box red hide-reds">Red</div>
</div>
&#13;
&#13;
&#13;

jsFiddle demo

关于flex-basis: 40%的注意事项:

flex-grow: 1速记中定义flex(请参阅.red),flex-basis不需要50%,这实际上会导致由于边距,每行一项(请参阅.box)。

由于flex-grow将消耗行上的可用空间,flex-basis只需要足够大以强制执行换行。在这种情况下,使用flex-basis: 40%,边距有足够的空间,但没有足够的空间容纳第三个项目。