JLT*_*JLT 4 html css media-queries flexbox
我有 10 个 div:2 个隐藏的和 8 个堆叠在一起的。
使用媒体查询,在调整屏幕大小时,我可以显示 2 个隐藏的 div。
所以,现在我在底部有 4 个红色 div,但我希望它们成对出现 - 2 行,2 个红色 div,一个挨着一个。

我怎么做?
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;
}
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
你的容器有flex-direction: column. 您的布局只有一列。但是没有办法将 flex 项目并排包装在一个列中。Flexbox 不是这样工作的。
但是,您的布局可以使用flex-direction: row和flex-wrap: wrap。通过给每个 item width: 100%,每个 item 强制下一个 item 到下一行。这将创建一列堆叠项目。然后,给出最后四个项目width: 50%,所以每行有两个。
.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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
注意事项flex-basis: 40%:
随着flex-grow: 1中定义的flex简写(见.red),有没有必要flex-basis为50%,这实际上是由于利润率(参见导致一列一个项目.box)。
由于flex-grow会消耗行上的可用空间,因此flex-basis只需要足够大以强制换行。在这种情况下,使用flex-basis: 40%,边距有足够的空间,但没有足够的空间容纳第三个项目。