Html 使用 Flex Box 将列移动到下一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23863680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving column to next line using Flex Box
提问by Aamir Shahzad
I have three columns, ordering 1,2,3.
我有三列,顺序是 1、2、3。
HTML
HTML
<div class="flex-container">
<div class="item first">1</div>
<div class="item second">2</div>
<div class="item third">3</div>
</div>
CSS
CSS
.flex-container {
display: flex;
}
.item {
background: orange;
padding: 10px auto;
color: #fff;
font-family: arial;
flex-grow: 100;
flex-shrink: 50;
text-align: center;
}
.first {
order: 1;
}
.second {
order: 2;
}
.third {
order: 3;
}
What I want when I switch to mobile screen columns should display like this;
当我切换到移动屏幕列时,我想要的内容应该像这样显示;
1 3
2
Media Query
媒体查询
/* Too narrow to support three columns */
@media all and (max-width: 640px) {
.second {
order: 3;
/* And go to second line */
}
.third {
order: 2;
}
}
Column two should move to next line.
第二列应移至下一行。
How can I do this?
我怎样才能做到这一点?
回答by King King
By default the flex-direction
is row
, you should change it to column
and use flex-wrap:wrap
(we can write it shortly using flex-flow:column wrap
). Note that to make the third column jump to the next column, the .flex-container
's height should be large enough to contain all the .first
and .second
butnot enough to contain all 3 items. With just that, you can recognize that the .third
expand/strecth the whole space (on the second column). So you can try setting its flex-grow:0
and use flex-basis:50%
. Here is the code:
默认情况下flex-direction
is row
,您应该将其更改为column
并使用flex-wrap:wrap
(我们可以很快使用 编写它flex-flow:column wrap
)。请注意,要使第三列跳转到下一列,.flex-container
的高度应足够大以包含所有项目.first
,.second
但不足以包含所有 3 个项目。仅此.third
而已,您就可以识别扩展/拉伸整个空间(在第二列上)。所以你可以尝试设置它flex-grow:0
并使用flex-basis:50%
. 这是代码:
@media all and (max-width: 640px) {
.flex-container {
flex-flow:column wrap;
height:40px;
}
.third {
flex-grow:0;
flex-basis:50%;
}
}
Demo.
演示。
Here is another solution using column boxlayout instead of flex-box, it works very well indeed.
这是另一个使用列框布局而不是flex-box 的解决方案,它确实工作得很好。