先避免弯曲包装,然后在较小的屏幕上包装


有一个父div.main包含两个子div.child。我已经将父div设置为flex-wrap: wrap;,但当屏幕宽度足够宽时,子div会被包装在第一个位置。

.main {
background-color: gray;
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
<div class="main">
<div class="child"></div>
<div class="child"></div>
</div>

一开始应该是这样的

.main {
background-color: gray;
display: flex;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
width: 70%
}
.child:last-child {
width: 30%
}
<div class="main">
<div class="child"></div>
<div class="child"></div>
</div>

当屏幕宽度很小时,它们应该包装

.main {
background-color: gray;
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
width: 100%;
}
<div class="main">
<div class="child"></div>
<div class="child"></div>
</div>

您可以使用媒体查询来告诉它何时进行弹性包装。看看我在这里做了什么:

@media screen and (max-width: 480px) {
.main {
flex-wrap: wrap;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
}

.main {
background-color: gray;
display: flex;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
width: 70%
}
.child:last-child {
width: 30%
}
<div class="main">
<div class="child"></div>
<div class="child"></div>
</div>

只需使用媒体查询指示浏览器在.main上使用flex-wrap: wrap;即可。

在本例中,我在800px处将其设置为wrap

.main {
background-color: gray;
display: flex;
flex-wrap: no-wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
.child:first-child {
flex: 1 0 70%;
}
.child:last-child {
flex: 1 0 30%;
}
@media only screen and (max-width: 800px) {
.main {
flex-wrap: wrap;
}
}
<div class="main">
<div class="child"></div>
<div class="child"></div>
</div>

为了避免媒体查询,您可以设置一个flex grow值和一个最小宽度。最小宽度设置将触发包装。

最小宽度设置为触发大约700px的中断的示例:

.main {
background-color: gray;
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
}
.child {
background-color: green;
height: 50px;
}
/* average break point set at 700px 
min-size at break point - 10px(gap + padding/2)   * 0.3 & 0.7 for each div*/
.child:first-child {
flex: 7 0 auto;
min-width: calc( 700px - (700px * 0.3) - 10px);
}
.child:last-child {
flex: 3 0 auto;
min-width: calc( 700px - (700px * 0.7) - 10px);
}
<div class="main">
<div class="child">Play me full page then resize the window to check my behavior</div>
<div class="child"></div>
</div>

相关内容

最新更新