Arrange 2 items per row using flexbox

末鹿安然 提交于 2020-08-17 13:03:18

问题


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?


回答1:


you can give flex: 0 50% to children divs without touching .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>



回答2:


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.

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.

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.

Good luck!



来源:https://stackoverflow.com/questions/45037844/arrange-2-items-per-row-using-flexbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!