我有一个带有 4 个包含图像和文本的内部 div 的 flexbox。允许 flexbox 包装:flex-wrap: wrap
在普通的笔记本电脑屏幕上,元素排成一排,如下所示:
元素元素元素,
当窗口缩小时,最后一个 flex 元素在新的一行中下降,如下所示:
元素元素元素
元素
这样我在第一行有 3 个元素,在第二行有 1 个。
我需要的是只能成对打破的行。不要连续 3 个,新的一行 1 个,连续 4 个,或者连续 2/2 个。
我还需要将元素缩小一点,但我找到了解决方法。
<div class = "flex">
<div class = "f4">
<a href = "...">
<img ... width = "330" height = "247" >
<h3>Title</h3>
</a>
<p>the excertp ... </p>
</div>
<div class = "f4">
<a href = "...">
<img ... width = "330" height = "247" >
<h3>Title</h3>
</a>
<p>the excertp ... </p>
</div>
<div class = "f4">
<a href = "...">
<img ... width = "330" height = "247" >
<h3>Title</h3>
</a>
<p>the excertp ... </p>
</div>
<div class = "f4">
<a href = "...">
<img ... width = "330" height = "247" >
<h3>Title</h3>
</a>
<p>the excertp ... </p>
</div>
</div>
.flex {
display: flex;
justify-content: space-evenly;
flex-wrap: wrap;
}
.f4 {
flex-basis: 300px;
flex-grow: 1;
margin: 8px;
}
.f4 img {
max-width: 330px;
width: 100%;
height: auto;
}
编辑:
我让元素收缩到原始尺寸放不下 3 倍,这样我就不必添加额外的 wrapper 。
.f4 {
flex-basis: 243.5px;
flex-grow: 1;
max-width: 330px;
margin: 8px;
}
.f4 img {
width: 100%;
height: auto;
}
@media (max-width: 1038px) {
.f4 {
flex-basis: 330px;
}
}
最佳答案
没有办法自动解决所有情况(除了[1-2] 和[3-4] 的额外包装) .
"Extra wrapper" 对生成列表没有用(当列表的长度是动态的 - 例如博客页面列表)。
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
解决这个问题的最基本方法是媒体问:
您的布局是:
[25%]
[25%]
[25%]
[25%]
在较小的屏幕上:50%
50%
- 这就是媒体查询如此有用的原因。
*{
box-sizing: border-box;
}
.flex{
display: flex;
flex-wrap: wrap;
}
.col{
border: 1px solid lightgray;
flex-basis: 50%;
height: 200px;
/* align card */
display: flex;
align-items: center;
justify-content: center;
background: #e1f7ff;
}
@media only screen and (min-width: 992px) {
.col{
flex-basis: 25%;
}
}
<main class="flex">
<div class="col">col 1</div>
<div class="col">col 2</div>
<div class="col">col 3</div>
<div class="col">col 4</div>
</main>
关于css - 成对的 flex-wrap 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61336986/