Html 使用 flexbox 每行排列 2 个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45037844/
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
Arrange 2 items per row using flexbox
提问by PranavPinarayi
Imagine I have following markup
想象一下我有以下标记
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
and style
和风格
.item {
width: 100%
}
and due to certain reasons I can't change the width of the
.item
Can I arrange 2 items in each row by styling parent container .container
, using flexbox or any other way?
并且由于某些原因,我无法.item
通过设置父容器样式.container
、使用 flexbox 或任何其他方式来更改每行 2 个项目的宽度
?
回答by dippas
you can give flex: 0 50%
to children divs without touching .item
您可以flex: 0 50%
在不接触的情况下给孩子 div。item
.item {
width: 100%
}
.container {
display: flex;
flex-wrap: wrap;
}
.container>div {
flex: 0 50%;
/*demo*/
border: red solid;
box-sizing:border-box
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
回答by Ben
Assuming that the width property must not be changed, I can think of a few possible solutions, the first being fit-content
which has amazingly poor browser support. The second, is use positioning, which is an equally bad idea due to its finicky nature and likelihood to fail on different screen sizes.
假设宽度属性不能改变,我可以想到几个可能的解决方案,第一个是fit-content
浏览器支持非常差。第二,使用定位,由于其挑剔的性质和在不同屏幕尺寸上失败的可能性,这同样是一个坏主意。
Now the last two, are very similar, one is to use two containers, give them display:inline;
give them a limited width, and fill them with items. If you didn't notice, this is essentially a 2×1 table.
现在最后两个,非常相似,一个是使用两个容器,display:inline;
给它们一个有限的宽度,并用物品填充它们。如果您没有注意到,这实际上是一个 2×1 的表。
Lastly you could make a 2×1 table, and while it is probably the easiest solution here, it is a bad idea to get in the habit of using tables to position things other than forms and tables. However, it is an option that I will make available to you.
最后你可以制作一个 2×1 的表格,虽然这可能是这里最简单的解决方案,但养成使用表格来定位表格和表格以外的东西的习惯是一个坏主意。但是,这是我将提供给您的一个选项。
Good luck!
祝你好运!