响应式弹性框,每行3个项目,然后是2个,然后是1个 [英] Responsive flexbox with 3 items per row, then 2, then 1
问题描述
我有一个包含六个项目的部分.
I have a section which contain six items.
我希望在台式机上每行3个项目,在中型设备上,我希望每行2个项目,在移动设备上,我希望每行1个项目
I want 3 items per row on desktop, and on medium device I want 2 items per row, and 1 one Item per on mobile device
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
这是CSS:
.flex-container{
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
@media only screen and (max-width: 768px) and (min-width: 320px){
.flex-container {
display: flex;
justify-content: center;
flex-basis: 100%;
}
}
这向我显示了台式机上只有3个项目,而移动设备上只有1个项目,但没有2个项目,我需要更改代码以获取所需的内容吗?
This shows me only 3 items on desktop and one per item in mobile, but no 2 items, what do I need to change in my code to get what I want?
推荐答案
可以通过在媒体查询中调整 flex-basis
来实现布局.
The layout can be achieved by adjusting flex-basis
inside media queries.
这里是个主意:
.flex-container {
display: flex;
flex-wrap: wrap;
}
.flex-container > div {
flex: 1 0 26%;
}
@media ( max-width: 768px) {
.flex-container > div {
flex-basis: 34%;
}
}
@media ( max-width: 320px) {
.flex-container > div {
flex-basis: 51%;
}
}
/* non-essential demo styles */
.flex-container > div {
height: 50px;
background-color: lightgreen;
border: 2px solid white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
在第一个 flex
规则中, flex-grow
设置为 1
.这意味着弹性项目将消耗所有可用空间.
In the first flex
rule, flex-grow
is set to 1
. That means the flex items will consume all free space.
因此,每个项目的宽度(通过 flex-basis
表示)不再是传统的33.33%(每行3个项目),50%(每行2个项目)和100%
Hence, the width of each item, expressed through flex-basis
, no longer needs to be the traditional 33.33% (3 items per row), 50% (2 per row) and 100%.
通常必须手动调整这些数字(例如 calc()
),以留出一些空白.
These numbers often have to be manually adjusted (e.g., calc()
) to make space for margins.
在这种情况下,得益于flex技术, flex-grow
会消耗剩余空间,而 flex-basis
只需足够大即可执行换行.
In this case, thanks to flex technology, flex-grow
consumes remaining space and flex-basis
needs only to be large enough to enforce a wrap.
因此,例如,使用 flex-basis:26%
,行上只能容纳三个项目.第四个必须包装.有足够的利润空间. flex-grow
填充空白空间.
So, for example, with flex-basis: 26%
, only three items can fit on the line. The fourth must wrap. There's plenty of room for margins. flex-grow
fills up empty space.
这篇关于响应式弹性框,每行3个项目,然后是2个,然后是1个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!